Display invalid output when reading from file in java

Running this program shows an incorrect output. My file "values.txt" contains 45678 , and the output
after starting the program 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(); } } 
+5
source share
2 answers

First you assign numbers[index] , then increment index and print numbers[index] (for the next empty value).

Change index++ and System.out calls.

+4
source

Move index++ after calling System.out.println .

At the moment, you always output the unassigned numbers . (In Java, every element in an int array is initialized to zero).

An alternative would be to completely abandon index++; and write System.out.println(numbers[index++]); . I personally find this more clear.

+3
source

Source: https://habr.com/ru/post/1207717/


All Articles