-1

I am reading a string from a file, and parse the string and the different elements into an array for later manipulation.

Every thing works fine, however when printing elements inside the WHILE loop it works, however, when I try to print the array out of the while loop I get an array Null pointer. Here is the code :

public PointsEX2(){
        String temp = new String();
        String[] parse =null;

        File file = new File("C:/Users/DjKidoo/Desktop/IA/mof.txt");
        Scanner sc = null;

        for(int t=0;t<pt_tab1.length;t++){
            pt_tab1[t]=new PointEX2();
        }



        try {
            sc = new Scanner(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        int j=0;

        while ((sc.hasNextLine())&& (j<= pt_tab1.length)) {
            temp = sc.next();
            parse = temp.split(",",0);
            pt_tab1[j]= new 
  PointEX2(Float.parseFloat(parse[0]),Float.parseFloat(parse[1]),Float.parseFloat(parse[2]),Float.parseFloat(parse[3]),parse[4]);

 System.out.println(toString(pt_tab1[j])); // perfectly works

        }


        for (int i=0;i<pt_tab1.length;i++)
        System.out.println(pt_tab1[i].x); // Array Null Pointer
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
djkidoo
  • 1
  • 2

1 Answers1

1

You never increment j within your while loop, so it remains 0 and so you continually assign a new PointEX2 into the same array item, pt_tab1[0]. All the others are null.

pt_tab1 shouldn't even be an array but rather an ArrayList<PointEX2>, and then you wouldn't have this problem.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • I hace an other question if you want, when ever we have an array to be used in our code, is it recomonded to instantiate it in the constructor of the class where it was declared, or, just assign a reference in that class and instantiate it in Main, and please why you asked me to use arrayLists instead of tables ? what is the advantage of using them in this case. Thank you – djkidoo Nov 03 '18 at 10:32