James B
James B

Reputation: 231

Adding numbers together from a file

I'm trying to read in integers from a file, then display them and add them together and then display the total. My code is not working however, sum += scan.nextInt(); is causing errors. Can someone please help me?

import java.util.Scanner;
import java.io.File;
public class HandlingExceptions {

public static void main(String[] args) throws Exception {
    int sum = 0;

    File numbersFile = new File("numbers.txt");

    Scanner scan = new Scanner(numbersFile);

    while(scan.hasNextInt()){
        System.out.println(scan.nextInt());
        sum += scan.nextInt();
    }

    System.out.println(sum);

    scan.close();
    }

}

The console shows the following at runtime:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at HandlingExceptions.main(HandlingExceptions.java:20)

Upvotes: 2

Views: 45

Answers (1)

StackFlowed
StackFlowed

Reputation: 6816

This code is problematic as you are consuming one number to print and other to add. Another problem would be if you had odd numbers in the scanner then you would run into NoSuchElementException

while(scan.hasNextInt()){
    System.out.println(scan.nextInt());
    sum += scan.nextInt();
}

Change it to :

while(scan.hasNextInt()){
    int tempInt = scan.nextInt();
    System.out.println(tempInt);
    sum += tempInt;
}

Upvotes: 2

Related Questions