End of entry Java Scanner

3

This code in C will read integers until you type Control-Z (end of entry in windows).

void main(int argc, char *argv[]) {
    char line[100];
    int sum = 0;

    while(scanf("%s", line) == 1) {
        sum += atoi(line);
    }

    printf("%d\n", sum);
}

How do I do the same using Scanner in Java?

    
asked by anonymous 03.04.2014 / 16:52

2 answers

4

One possible solution would look like this:

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int sum = 0;
        while (s.hasNextLine()) {
            String nextLine = s.nextLine();
            sum += Integer.parseInt(nextLine);
        }
        System.out.println(sum);
    }
}
    
03.04.2014 / 17:02
1

You can use the class documentation to understand the methods it has: < strong> Scanner .

Here is a simple example (not tested):

import java.util.Scanner;

public class SimpleScanner {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int sum = 0;
        while (s.hasNextInt()) {
            sum += s.nextInt();
        }

        System.out.println(sum);
    }
}

The loop would be equivalent to the following in C ++:

int i;
while (cin >> i) {
    sum += i;
}
    
03.04.2014 / 17:35