5

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();
    }
}
1
  • replace your while loop with while(ab.hasNext() && index<numbers.length) { numbers[index]=ab.nextInt(); System.out.println(numbers[index]); index++; } Commented Nov 26, 2014 at 8:18

2 Answers 2

4

You first assign to numbers[index] then increase index and output numbers[index] (for the next empty value).

Swap index++ and System.out calls.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.