6abhishek jha
6abhishek jha

Reputation: 57

Showing wrong output while reading from file in java

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

Answers (2)

Bathsheba
Bathsheba

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

StanislavL
StanislavL

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

Related Questions