sla*_*iyy 5 java string integer
我用了
int num = Integer.parseInt(str)
Run Code Online (Sandbox Code Playgroud)
将整数值写入字符串.我需要一个从给定字符串中读取这些值并计算其总和的函数.
示例:输入 - "43 68 9 23 318"输出 - 461
String str = "43 68 9 23 318";
int num = Integer.parseInt(str)
Run Code Online (Sandbox Code Playgroud)
你正在做的是,尝试一次解析完整的输入字符串,这将抛出NumberFormatException.您需要先拆分它,然后对每个返回的值执行求和String.
拆分输入字符串,whitespace然后解析每个数字并执行求和.
public static void main(String[] args) {
String input = "43 68 9 23 318";
String numbers[] = input.split("\\s+"); // Split the input string.
int sum = 0;
for (String number : numbers) { // loop through all the number in the string array
Integer n = Integer.parseInt(number); // parse each number
sum += n; // sum the numbers
}
System.out.println(sum); // print the result.
}
Run Code Online (Sandbox Code Playgroud)
在Java 8中,使用流
String input = "43 68 9 23 318";
String numbers[] = input.split("\\s+");
int[] nums = Arrays.stream(numbers.substring(1, numbers.length()-1).split(","))
.map(String::trim).mapToInt(Integer::parseInt).toArray();
int sum = IntStream.of(nums).sum();
System.out.println("The sum is " + sum);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21379 次 |
| 最近记录: |