0

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));

2 Answers 2

3

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

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

Comments

2

Mika is right -- you need to repeat the scanner = new Scanner(...) after your // n is now 26 line.

Or, better, use an ArrayList<Integer>() rather than int[], then you only need a single pass:

public static void main(String[] args) throws Exception {
    List<Integer> numbers = new ArrayList<>();
    Scanner scanner = new Scanner(new File("numbers.txt"));
    while (scanner.hasNextInt()) {
        numbers.add(scanner.nextInt());
    }
    System.out.print(numbers);
}

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.