题目描述
计算一系列数的和
输入描述:
输入数据有多组, 每行表示一组输入数据。
每行不定有n个整数,空格隔开。(1 <= n <= 100)。
输出描述:
每组数据输出求和的结果
输入
1 2 3
4 5
0 0 0 0 0
输出
6
9
0
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String[] s = sc.nextLine().split(" ");
int sum = 0;
for(int i = 0;i<s.length;i++){
sum += Integer.parseInt(s[i]);
}
System.out.println(sum);
}
}
}
nextLine()方法返回的是Enter键之前的所有字符,它是可以得到带空格的字符串的。
next()会自动消去有效字符前的空格,只返回输入的字符,不能得到带空格的字符串。
next()在输入有效字符之后,将其后输入的空格键、Tab键或Enter键等视为分隔符或结束符。
nextLine()方法的结束符只是Enter键
String[] s = sc.nextLine().split(" "); : 把输入的字符串以“ ”(即空格)为条件分割成一个String数组。
为了更清晰的理解原理
也可以写为
String str = sc.nextLine(); //nextLine方法返回值是String类型
String[]s = str.spilt(" "); //split方法返回值是String数组类型