Evgenij Reznik
Evgenij Reznik

Reputation: 18614

Add up numbers from file

I have a text file numbers.txt with some lines with numbers, separated by a comma (\n is not visible, of course):

1, 2, 3, 4, 5, \n
6, 7, 8, 9, 10, \n
11, 12, 13, 14, 15

I want to read and add up them, so that the overall result would be 120.
This is my code:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class App1 {

    int res;

    public App1() {
     Scanner sc = null;
        try {
            sc = new Scanner(new File("numbers.txt")).useDelimiter(",");
        } catch (FileNotFoundException ex) {
            System.err.println(ex);
        }
      while (sc.hasNextInt()) {
        res += sc.nextInt();
      }
        System.out.println("Result: " + res);
    }

    public static void main(String[] args) {
        App1 app = new App1();
    }
}

Unfortunately I only get the first number:

Result: 1

Upvotes: 2

Views: 91

Answers (2)

Pshemo
Pshemo

Reputation: 124275

Try with useDelimiter("[,\\s]+"). Currently you are replacing standard delimiter \p{javaWhitespace}+ with only , which means that after finding first integer scanner will be

1,| 2, 3, 4, 5, \n
  ^here

so next characters will be [space][digit]. Since space is not delimiter anymore and is definitely not digit this data can't be accepted in hasNextInt() test.

Upvotes: 3

Paul Samsotha
Paul Samsotha

Reputation: 209062

Try .useDelimiter("[,\\s]+");. If you're only using delimiter(","), the next char is whitespace, and you can't use hasNextInt() on white space.

Upvotes: 2

Related Questions