Tuesday 15 March 2011

java - Reading from file into Array -



java - Reading from file into Array -

i have file numbers. looks follows:

1 2 3 4 5 6 7 8 9 10

the problem occurs while reading numbers array.

here piece of code:

scanner file1 = new scanner( new file("file1.txt") ); int lengt_h = 0; // here eclipse crashes... while( file1.hasnext() ) lengt_h++; int[] numberarray = new int[lengt_h]; for(int i=0; i<numberarray.length; i++) { numberarray[i] = file1.nextint(); } for(int n: numberarray) system.out.print(numberarray[n] + " ");

even if alter hasnext() function constant length (e.g 10), numbers in numberarray array looks follows:

1 1 1 2 1 1 5 5 1 3

why code not work properly?

problem code not moving sacanner pointer in while loop infinite loop. in lastly for loop trying access element numberarray[n] wrong because n number array numberarray.

you can seek :

public static void main(string args[]) throws filenotfoundexception { scanner file1 = new scanner(new file("d:\\data.txt")); int lengt_h = 0; while (file1.hasnext()) { lengt_h++; file1.next(); } file1 = new scanner(new file("d:\\data.txt")); // 1 time again set file pointer @ origin int[] numberarray = new int[lengt_h]; (int = 0; < numberarray.length; i++) { numberarray[i] = file1.nextint(); // read integer file } (int n : numberarray) system.out.print(n + " "); }

java arrays file

No comments:

Post a Comment