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