-2

Enter any number of integer values in a single row separated by space and the calculate and print the sum to next line.

EX: input: 1 2 3 4 output: 10

2 Answers2

3

This should work - console.hasNext uses whitespace as its delimiter.

Scanner console = new Scanner(System.in);
int sum = 0;
while (console.hasNext()) {
    sum += console.nextInt();
}
System.out.print(sum);
Michael
  • 776
  • 4
  • 19
0

You can read the whole line as a String and than split it into a String array and than you can add it one by one for this purpose as following:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String s[] = br.readLine().split(" ");
    int sum=0;
    for(int i=0;i<s.length;i++){
        sum+=Integer.parseInt(s[i]);
    }
    System.out.println(sum);

for this you have to import :

import java.io.BufferedReader;
import java.io.InputStreamReader;

This is faster than Scanner, see this question for more details about Scanner and BufferedReader.

Community
  • 1
  • 1
Kaushal28
  • 5,377
  • 5
  • 41
  • 72