我有這張表(2d數組),我使用了一個數字0-4的隨機工具來選擇一個行和一列來替換一個帶有字母「P」的數字,我擁有一切,但我得到了這個。如何用一個字符串類型替換二維數組中的一個整數元素,使用隨機
- Type mismatch: cannot convert from String
to int
- Type mismatch: cannot convert from
Random to int
- Type mismatch: cannot convert from
Random to int
同時這個問題How to change value of array element in 2D arrays?說你可以做
someArray[row][column] = "x";
這裏是我有什麼(我想我的問題是使用隨機)
import java.util.Random;
public class Server{
private int number;
private boolean pennyLanded;
public Server()
{
int n = 0;
number = n;
pennyLanded = false;
}
public boolean pennyLanded()
{
return pennyLanded;
}
public void setPennyLanded()
{
pennyLanded = true;
}
public int getNumber()
{
return number;
}
public String toString()
{
if (pennyLanded)
return "P";
else
return "" + number;
}
public static int[][] tableMaker(){
int[][] table = new int[5][5];
for(int i=0; i<table.length; i++){
for(int j=0; j<table.length; j++){
if(i==2 && j==2){
table[i][j] =3;
}
else if(i==0 || i==4){
table[i][j] = 1;
}
else if(j==4 || j==0){
table[i][j] = 1;
}
else if((i==1 || i==3) && (j>0 || j<4)){
table[i][j] = 2;
}
else if((i==2 && j==1) || (i==2 && j==3)){
table[i][j] = 2;
}
}
}
for(int i=0; i<table.length; i++){
for(int j=0; j<table.length; j++){
System.out.print(table[i][j] + " ");
}
System.out.println();
}
return table;
}
public static int[][] tossPenny(){
Random row = new Random();
Random column = new Random();
int[][] table = Server.tableMaker();
for(int i=0; i<5; i++){
table[row.nextInt(4)][column.nextInt(4)] = -1;
}
return table;
}
}
表打印客戶類別
public class Client{
public static void main(String[] args){
System.out.println(Server.tableMaker());
}
}
我不知道怎麼簡單的修復,這是的,我已搜查我只是有一個特別的問題
表打印爲使
1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1
而且我想是這樣說隨機拿出1和2
1 1 1 1 1
1 2 P 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1
Integer.valueOf方法。研究一下。 http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html – Kon
這有幾個問題。其中一個主要原因是你試圖將一個String變量賦給一個二維的int數組。您應該使用'String'的二維數組,並在放入之前轉換所有數字;或者使用一個特殊的'int'值(例如-1)來表示該便士。還有其他問題,但這應該讓你開始。 –
是的,我有一個[[我@ 690aefdb問題需要修復,但我現在試圖忽略,直到我可以得到實際的工作,雖然 –