我的挑战是使用用户输入查找字符串中元素的总值。 用户输入应如下:1,2,3,4,5,6,7 ......
当我尝试使用StringTokenizer
时遇到问题所以我使用了split()方法,但是根据我是否使用(i + i)或( + = i)在第二个for循环中。
// Libraries
import java.util.Scanner;
import java.util.StringTokenizer;
public class Project_09_8
{
public static void main(String[] args)
{
// Create instance of Scanner class
Scanner kb = new Scanner(System.in);
// Variables
String input; // Holds user input
String [] result; // Holds input tokens in an array
int i = 0; // Counter for loop control
// User input
System.out.print("Please enter a positive whole number, separated by commas: ");
input = kb.nextLine();
result = input.split(",");
// Converts input String Array to Int Array
int [] numbers = new int [result.length];
// Loop through input to obtain each substring
for (String str: result) {
numbers[i] = Integer.parseInt(str);
i++;
}
// Receive this output when printing to console after above for loop [I@10ad1355.
/*
// Loop to determine total of int array
int sum = 0; // Loop control variable
for (int j : numbers) {
sum += i;
//sum = i + i;
}
// Print output to screen
System.out.println("\nThe total for the numbers you entered is: " + sum);
*/
} // End main method
} // End class
答案 0 :(得分:2)
在Java 8
中,您可以让自己摆脱痛苦
代码:
String s = "1,2,3,4,5,6,7";
String[] sp = s.split(",");
//Stream class accept array like Stream.of(array)
// convert all String elements to integer type by using map
// add all elements to derive summation by using reduce
int sum = Stream.of(sp)
.map( i -> Integer.parseInt(i))
.reduce(0, (a,b) -> a+b);
System.out.println(sum);
输出:
28
答案 1 :(得分:1)
由于您已经在使用Scanner
,因此可以使用useDelimiter方法为您分割逗号。
扫描程序还有一个nextInt()
来解析/从String转换为int
Scanner s = new Scanner(System.in)
.useDelimiter("\\s*,\\s*");
int sum = 0;
while(s.hasNextInt()){
sum += s.nextInt();
}
System.out.println(sum);
答案 2 :(得分:0)
我建议您使用\\s*,\\s*
拆分(可选)空格,在需要时声明变量并在一个循环中添加总和(不转换为int[]
副本),例如,
public static void main(String[] args) {
// Create instance of Scanner class
Scanner kb = new Scanner(System.in);
System.out.print("Please enter a positive whole number, "
+ "separated by commas: ");
String input = kb.nextLine();
String[] result = input.split("\\s*,\\s*");
int sum = 0;
for (String str : result) {
sum += Integer.parseInt(str);
}
System.out.println(Arrays.toString(result));
System.out.printf("The sum is %d.%n", sum);
}