[英]how to Read a file and store the values in a 2-Dimensional Array using Scanner
Suppose I have a file in this format, 假设我有一个这种格式的文件,
8 15 8 15
5 5
8 8
16 16
89 89
I am using Scanner class for reading the file. 我正在使用Scanner类读取文件。 I want to store these values in a 2-dimensional array, for example 我想将这些值存储在二维数组中
y[0][0]=8,y[0][1]=15,y[1][0]=5,y[2][0]=8. y [0] [0] = 8,y [0] [1] = 15,y [1] [0] = 5,y [2] [0] = 8。
I am not able to store the values like this. 我无法存储这样的值。 I am getting an output 我正在输出
y[0][0]=8,y[0][1]=15,y[0][3]=5,y[0][4]=8. y [0] [0] = 8,y [0] [1] = 15,y [0] [3] = 5,y [0] [4] = 8。
I like to know how can I find (EOL)end of line in the file, so that it automatically stores in 2-D array. 我想知道如何在文件中找到(EOL)行尾,以便它自动存储在二维数组中。
public class gjd {
public static void main(String[] args) {
java.io.File test2 = new java.io.File("c.txt");
try
{
Scanner input = new Scanner(test2);
while (input.hasNextLine()){
int y[][]=new int[10][10];
for(int i=0;i<test2.length();i++)
{
for(int o=0;o<test2.length();o++)
{
y[i][o]=input.nextInt();
System.out.println(y[i][o]);
}
}
}
} catch (Exception e){
System.out.println("could not find file");
}
}
}
Try this code.... 试试这个代码。
java.io.File test2 = new java.io.File("C:/c.txt");
Scanner input = new Scanner(test2);
String arr[][]=new String[5][5];
int i=0,j=0;
while(input.hasNext())
{
String val=input.nextLine();
j=0;
if(val.contains(" "))
{
String str[]=val.split(" ");
int cn=str.length;
while(cn>0)
{
arr[i][j]=str[j];
cn--;
j++;
}
}
else
arr[i][j]=val;
i++;
}
for(int i1=0;i1<5;i1++)
{
for(int j1=0;j1<5;j1++)
if(arr[i1][j1] != null)
System.out.print(arr[i1][j1]);
System.out.println();
}
You should not be instantiating an array every time you find a line: 您不应在每次找到一行时都实例化数组:
int y[][] = new int[10][10];
should not be in the while loop. 不应该在while循环中。
And what are you trying to do with the length of the file: test2.length()
? 您要如何处理文件的长度: test2.length()
?
you could use a second scanner working with the line having parsed from the first scanner 您可以使用第二台扫描仪,处理从第一台扫描仪解析的行
then you can check, whether there is another another int in the line, set a default value if needed. 然后可以检查行中是否还有另一个int,如果需要,请设置默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.