Reputation: 57
Running this program shows the wrong output. My file "values.txt" contains 45678
and the output
after running the program is 00000
.
import java.util.Scanner;
public class array{
public static void main(String[] args)throws IOException
{
final int SIZE = 6;
int[] numbers = new int[SIZE];
int index = 0;
File fl = new File("values.txt");
Scanner ab = new Scanner(fl);
while(ab.hasNext() && index < numbers.length)
{
numbers[index] = ab.nextInt();
index++;
System.out.println(numbers[index]);
}
ab.close();
}
}
Upvotes: 5
Views: 120
Reputation: 234885
Move index++
to after the System.out.println
call.
At the moment you're always outputting an unassigned value of numbers
. (In Java every element in an array of int
is initialised to zero).
An alternative would be to discard index++;
entirely and write System.out.println(numbers[index++]);
. I personally find that clearer.
Upvotes: 4
Reputation: 57421
You first assign to numbers[index]
then increase index
and output numbers[index]
(for the next empty value).
Swap index++
and System.out
calls.
Upvotes: 4