End of Java Scanner input

Asked

Viewed 307 times

3

This C code reads integers until Control-Z is typed (end of windows entry).

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 I do the same using the Scanner in Java ?

  • Welcome to Stack Overflow in English. Your question is about how to simulate the Java scanf with the input up to CTRL+Z or you just want to know how to input data in Java?

2 answers

4


A possible solution would be thus:

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

1

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

Follow a simple example (untested):

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.