对于课程我应该写一个数字扫描仪,打印用户输入,这些数字的总和和乘积。我们可以假设用户在每个数字后输入一个空格,用户可以输入任意数量的数字。例:3 10 2 你的电话号码是:3 10 2 总和:15 产品:60
public static void substringGrabber () {
String recentInt;
int lastDigit = 0;
int parsedInt = 0;
for (int i = 0; i < numbers.length(); i++) {
if (! Character.isDigit(numbers.charAt(i))) {
char ignoredCharacter = numbers.charAt(i);
if (ignoredCharacter != ' ') {
System.out.println("Your input of:" + ignoredCharacter + " has been ignored");
}
recentInt = numbers.substring(lastDigit, i);
parsedInt = Integer.parseInt(recentInt);
sum += parsedInt;
product *= parsedInt;
lastDigit = i + 1;
finalString = finalString + parsedInt + " ";
}
}
System.out.println("Your numbers are: " + finalString);
System.out.println("Sum: " + sum);
System.out.println("Product: " + product);
}
答案 0 :(得分:1)
nextInt()
中的 Scanner
使用空格作为标记分隔符。因此,您的代码可能如下所示(事先询问他们将要输入多少个数字):
System.out.println("How many numbers?");
int numbers = scanner.nextInt();
int sum = 0;
int product = 0;
int[] arr = new arr[numbers];
for (int i = 0; i < numbers; i++){
System.out.println("Type in a number");
int input = scanner.nextInt();
sum += input;
arr[i] = input;
product *= input;
}
System.out.println("Your numbers are: " + Arrays.deepToString(arr));
System.out.println("Sum: " + sum);
System.out.println("Product: " + product);
答案 1 :(得分:0)
如果在测试字符串的末尾添加一个空格,它将起作用。
此检查!Character.isDigit(numbers.charAt(i))忽略最后一位数。
所以更改逻辑以考虑那种情况:你有一个数字,你就在你的字符串的末尾。