问题
i'm getting this error and i can't quite figure out how to fix it.
error:
incompatible types
found : int
required: int[]array[x] = Integer.parseInt(elements[0]);
here is the code for my method. The file being used is a text file of 1000 numbers, 2 per line with 500 lines, separated by commas.
Example:
1,2
16,92
109,7
the purpose of this block is to read all lines of the text file, and assign all numbers to the 2d integer array.
public static int[][] writeTypes(){
String position;
String[] elements = new String[2];
int x;
int y=1;
int array[][] = new int[500][2];
File TypesFile = new File("Types.txt");
try {
Scanner twoput = new Scanner(pkTypesFile);
for(x = 0; twoput.hasNext(); x++){
position = twoput.nextLine();
elements = position.split(",", 2);
array[x] = Integer.parseInt(elements[0]);
array[x][y] = Integer.parseInt(elements[1]);
System.out.println(array[x] + " " + array[x][y]);
}
} catch (Exception e) {
System.err.format("Types File does not exist.\n");
}
return array;
}
回答1:
You seem to be confused about indexing into multidimensional arrays. array
is a 2-dimensional array, meaning it's an array of arrays. new int[500][2]
creates an array of length 500, each element of which is an int[]
of length 2, each element of which is an int. The expression array[x]
selects one of the 500 int[]
arrays of length 2. The compile error is saying you can't assign an int to an int[]
. You need to provide another index to select one of the ints in the array denoted by array[x]
.
Specifically, you should change
array[x] = Integer.parseInt(elements[0]);
array[x][y] = Integer.parseInt(elements[1]);
System.out.println(array[x] + " " + array[x][y]);
to
array[x][0] = Integer.parseInt(elements[0]);
array[x][1] = Integer.parseInt(elements[1]);
System.out.println(array[x][0] + " " + array[x][1]);
The second index selects one of the ints in the int[]
, which you can then assign to.
来源:https://stackoverflow.com/questions/20585675/assign-split-string-to-parsed-int