[英]Why is my loop running one less time than I'd like?
For class I am supposed to write a number scanner that prints user input, the sum and product of these numbers. 在课堂上,我应该写一个数字扫描仪来打印用户输入,这些数字的总和和乘积。 We can assume the user enters a space after every number and the user may enter as many numbers as they'd like. 我们可以假设用户在每个数字之后输入一个空格,并且用户可以输入任意数量的数字。 Ex: 3 10 2 Your numbers are: 3 10 2 Sum: 15 Product: 60 例如: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);
}
nextInt()
which resides in Scanner
by default uses white-space as a token separator. 默认情况下,位于Scanner
的nextInt()
使用空格作为标记分隔符。 Therefore, your code can look like this (ask them in advance how many numbers they're going to type in): 因此,您的代码可能看起来像这样(事先询问他们要输入多少个数字):
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);
If you add a space at the end of your test string it will work. 如果在测试字符串的末尾添加空格,它将起作用。
this check !Character.isDigit(numbers.charAt(i)) ignores the last digit. 此检查!Character.isDigit(numbers.charAt(i))忽略最后一位。
so change the logic to account for that that case : you have a digit and you are at the end of your string. 因此请更改逻辑以解决该情况:您有一个数字,并且位于字符串的末尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.