Reputation:
I have a file with numbers. It looks as follows:
1 2
3 4
5 6
7 8
9 10
The problem occurs while reading the numbers into Array.
Here is a 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 I change a hasNext() function into constant length (e.g 10), then numbers in numberArray Array looks as follows:
1 1 1 2 1 1 5 5 1 3
Why the code does not work properly?
Upvotes: 1
Views: 164
Reputation: 6515
Sacanner
pointer in while loop
so it were infinite loop.for
loop you are trying to access element from numberArray[n]
which is wrong because n
itself is a number from your array numberArray
.you can try this :
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")); // again put file pointer at beginning
int[] numberArray = new int[lengt_h];
for (int i = 0; i < numberArray.length; i++) {
numberArray[i] = file1.nextInt(); // read integer from file
}
for (int n : numberArray)
System.out.print(n + " ");
}
Upvotes: 2
Reputation: 30146
Try this:
List<Integer> numberArray = new ArrayList<Integer>();
while (file1.hasNext())
numberArray.add(file1.nextInt());
for (Integer n : numberArray)
System.out.print(n + " ");
Upvotes: 0
Reputation: 37083
Check the hasNext method here http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNext%28%29
it says "The scanner does not advance past any input."
So to move it further you should move to next token.
Upvotes: 0
Reputation: 1211
while( file1.hasNext() ) lengt_h++; // infi loop
hasNext method returns true if and only if this scanner has another token
public boolean hasNext()
You are not reading next token and hence hasNext()
will always return true
[EDIT]
If you don't know the size of array in advance, its better to use ArrayList
[1] http://www.tutorialspoint.com/java/util/java_util_arraylist.htm
Upvotes: 1