javaarraysjava.util.scanner

Trouble reading numbers from file into array


There are 26 numbers in the numbers.txt file. Those 26 numbers are supposed to be read to arr but instead I get 26 zeroes in my array.

Scanner scanner = new Scanner(new File("numbers.txt"));
int n = 0;
int i = 0;
while (scanner.hasNextInt()) {
    scanner.next();
    n++;
} // n is now 26 
int[] arr = new int[n];
while (scanner.hasNextInt()) {
    for (i = 0; i < arr.length; i++) {
        arr[i] = scanner.nextInt();
    }
}
System.out.print(Arrays.toString(arr));

Solution

  • zeroes are default value for array. a scanner is "single-use", it's single-pass. you used it once, you have to create another (maybe by earlier having the File object in a variable and then using it to create both Scanners?) or somehow reverse its state. the second loop has zero iterations, it never hasNextInt anymore