zetbo
zetbo

Reputation: 78

Java - Adding up integers from a file

I'm having problems with adding integers that are in a file. The code works fine displaying the integers but as soon as I add "total += scanner.nextInt();" it skips every other integer (e.g if file contained - 10, 20, 30, 40, 50, it would only display 10, 30, 50. and display total of 60(?)), and gives me a NoSuchElementException. What am I doing wrong here?

import java.io.File;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class AddingInts {

    public static void main(String[] args) {

        File myFile = new File("ints.txt");
        Scanner scanner = null;
        int total = 0;

        System.out.println("Integers:");

            try {
                scanner = new Scanner(myFile);

                while (scanner.hasNextInt()) {
                    System.out.println(scanner.nextInt());
                    //total += scanner.nextInt();
                }

            }
            catch (IOException ex) {
                System.err.println("File not found.");
            }
            catch (InputMismatchException ex) {
                System.out.println("Invalid data type.");
            }
            catch (NoSuchElementException ex) {
                System.out.println("No element");
            }
            finally {
                if (scanner != null) {
                    scanner.close();
                }
            }

            System.out.println("Total = " + total);
        }

}

Upvotes: 1

Views: 55

Answers (2)

elhuhdron
elhuhdron

Reputation: 36

Add a temp variable in your while loop:

            while (scanner.hasNextInt()) {
                int cur = scanner.nextInt();
                System.out.println(cur);
                total += cur;
            }

Upvotes: 0

El Fufu
El Fufu

Reputation: 66

When you call scanner.nextInt() within the first print statement you index to the next number. So when you call it again you simply skip a value.

In other words if you have 10, 20, 30

System.out.print(scanner.nextInt())// performs nextInt() which prints 10 and moves to 20
total += scanner.nextInt(); //will use the value of 20 instead of 10 because you are currently at 20 and moves the pointer to 30

Upvotes: 1

Related Questions