gpt4 book ai didi

java - 为什么我的循环运行时间比我想要的少一次?

转载 作者:行者123 更新时间:2023-12-01 11:05:53 25 4
gpt4 key购买 nike

对于类(class),我应该编写一个数字扫描仪来打印用户输入、这些数字的总和和乘积。我们可以假设用户在每个数字后输入一个空格,并且用户可以输入任意数量的数字。例如: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);
}

最佳答案

默认情况下,驻留在 Scanner 中的

nextInt() 使用空格作为标记分隔符。因此,您的代码可以如下所示(提前询问他们要输入多少数字):

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);

关于java - 为什么我的循环运行时间比我想要的少一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32957703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com