【发布时间】:2017-09-09 15:20:30
【问题描述】:
嗨,我想用逗号分隔的值填充一个二维数组,像这样
3
1,2,3
4,5,6
7,8,0
第一个数字是数组的大小,下一个值是数组的值这是我现在的代码
//readfile
public static void leeArchivo()
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try
{
//read first value which is teh size of the array
size = Integer.parseInt(br.readLine());
System.out.println("size grid" + size);
int[][] tablero = new int[size][size];
//fill the array with the values
for (int i = 0; i < tablero.length; i++)
{
for (int j = 0; j < tablero[i].length; j++ )
{
tablero[i][j] = Integer.parseInt(br.readLine());
}
}
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
这个方法对我来说很好用,只是另一个问题,如果我想在另一个旁边插入另一个相同大小的二维数组,这会有效吗?
public static void leeArchivo()
{
Scanner s = new Scanner(System.in);
size = Integer.parseInt(s.nextLine());
tablero = new int[size][size];
boolean exit = false;
while (!exit) {
for (int i = 0; i < size; i++) {
//quit commas to fill array
String valuesStrArr[] = s.nextLine().split(",");
for (int j = 0; j < size; j++) {
tablero[i][j] = Integer.parseInt(valuesStrArr[j]);
}
if (i == size - 1)
exit = true;
}
}
}
例子:
3
1,2,3
4,5,6
7,8,0
1,2,3
8,0,4
7,6,5
【问题讨论】: