[英]I want to add values from a text file and add it in two dimensional java. But gives null pointer exception
I want to read a text file and add the contents to the two dimensional array in java. 我想读取一个文本文件,然后将内容添加到Java中的二维数组中。 but when i add these values to the array I am getting array out of bounds exception in java.
但是当我将这些值添加到数组中时,我在Java中获取数组超出范围的异常。
java.io.File test2 = new java.io.File("e:\\A.txt");
BufferedReader bw =new BufferedReader(new FileReader("e:\\A.txt"));
String s=bw.readLine();
while(bw.readLine()!=null)
{
counterRow++;
}
System.out.println(counterRow);
String sw=bw.readLine();
String[] words=s.split(",");
counterCol=words.length;
System.out.println(words.length);
@SuppressWarnings("resource")
Scanner input = new Scanner(test2);
String Data[][]=new String[counterRow][counterCol];
int i1=0,j1=0;
while(input.hasNext())
{
String val=input.nextLine();
j1=0;
if(val.contains(","))
{
String str[]=val.split(",");
int cn=str.length;
while(cn>0)
{
Data[i1][j1]=str[j1];
cn--;
j1++;
}
}
else
Data[i1][j1]=val;
i1++;
}
My input file is 我的输入文件是
69,79,82 69,79,82
72,82,84 72,82,84
39,70,75 39,70,75
69,88,68 69,88,68
38,72,61 38,72,61
39,60,40 39,60,40
36,32,44 36,32,44
50,71,55 50,71,55
36,47,47 36,47,47
80,81,90 80,81,90
Error : Exception in thread "main" 100sssssss java.lang.NullPointerException at com.associa.mining.AssociateRuleMiningAlgo.main(AssociateRuleMiningAlgo.java:200)
错误:“ main”线程中的异常100sssssss java.lang.NullPointerException,位于com.associa.mining.AssociateRuleMiningAlgo.main(AssociateRuleMiningAlgo.java:200)
Thats because you are trying to read after you have reached EOF 那是因为您在达到EOF之后尝试阅读
while(bw.readLine()!=null) // read till EOF
{
counterRow++;
}
System.out.println(counterRow);
String sw=bw.readLine(); // ERROR cant read, you have reached EOF
PS - you dont even seem to use the variable "sw". PS-您甚至似乎都没有使用变量“ sw”。
Change the if(val.contains(","))
condition to if(val!=null && val.contains(","))
将
if(val.contains(","))
条件更改为if(val!=null && val.contains(","))
compelete code 补码
String val=input.nextLine();
j1=0;
if(val!=null){
if(val.contains(","))
{
String str[]=val.split(",");
int cn=str.length;
while(cn>0)
{
Data[i1][j1]=str[j1];
cn--;
j1++;
}
}else
Data[i1][j1]=val;
i1++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.