简体   繁体   中英

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. but when i add these values to the array I am getting array out of bounds exception in 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

72,82,84

39,70,75

69,88,68

38,72,61

39,60,40

36,32,44

50,71,55

36,47,47

80,81,90

Error : Exception in thread "main" 100sssssss java.lang.NullPointerException at com.associa.mining.AssociateRuleMiningAlgo.main(AssociateRuleMiningAlgo.java:200)

Thats because you are trying to read after you have reached 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".

Change the if(val.contains(",")) condition to 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++;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM