[英]Fill a 2d array with text file, comma separated values
Hi i want to fill a 2d array with comma separated values like this 嗨,我想用逗号分隔的值填充二维数组
3
1,2,3
4,5,6
7,8,0
first number the size of the array, the next values are the values of the array this is my code at the moment 第一个数字是数组的大小,下一个值是数组的值,这是我目前的代码
//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();
}
}
This method is working fine for me, just another question, this will work if I want to insert another 2d array of the same size next to the other? 这个方法对我来说很好用,只是另一个问题,如果我想在另一个旁边插入另一个相同大小的2d数组,这个方法可以工作吗?
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;
}
}
}
Example: 例:
3
1,2,3
4,5,6
7,8,0
1,2,3
8,0,4
7,6,5
Scanner in = new Scanner(System.in);
int num = in.nextInt();
Use Scanner. 使用扫描仪。 Replace System.in with File. 用文件替换System.in。
First, you have to separate the elements. 首先,您必须分离元素。
You can do this using the String method split ( https://www.javatpoint.com/java-string-split ) 您可以使用String方法split( https://www.javatpoint.com/java-string-split )执行此操作
//fill the array with the values
for (int i = 0; i < tablero.length; i++)
{
String[] elements = br.readLine().split(",");
for (int j = 0; j < tablero[i].length; j++ )
{
tablero[i][j] = Integer.parseInt(elements[j]);
}
}
br.close();
Or you can use Scanner method, nextInt. 或者,您可以使用nextInt扫描仪方法。
Regarding perfomance, the first option is better. 关于性能,第一种选择更好。
Solution using Scanner 使用扫描仪的解决方案
Scanner s = new Scanner(System.in);
int size = Integer.parseInt(s.nextLine());
int[][] tablero = new int[size][size];
boolean exit = false;
while (!exit) {
for (int i = 0; i < size; i++) {
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.