当我尝试在下面运行此代码并输入任何数字时,出现此错误 -线程“主”中的异常java.lang.NumberFormatException:对于输入字符串:“”
如何解决?
答案 0 :(得分:0)
尝试
int n = scanner.nextInt();
代替
int n = Integer.parseInt(scanner.nextLine());
答案 1 :(得分:0)
@develo通过建议使用scanner.nextInt()
部分正确,但是如果这样做,您还需要删除对Integer.parseInt
的调用(.nextInt()
将返回{{1} },因此无需将其解析为int
)
但是,代码的核心问题是循环。您从0开始循环,而这样循环1太多:
Integer
将其更改为for (int i = 0; i <= n; i++ ) {
或for (int i = 0; i < n; i++ ) {
,它将正常工作。
这是大学还是大学的任务? :)(我儿子正在攻读CS学位,这种代码看起来很熟悉:))
此外,Java约定是,类名始终以大写字母开头-因此您的类名应为for (int i = 1; i <= n; i++ ) {
,文件名为SumOfNumbers
答案 2 :(得分:0)
您需要句柄NumberFormatException
。由于空白行不能转换为int
,因此您将得到需要处理的异常。
执行此操作的示例如下:
import java.util.Scanner;
public class SumOfNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = 0;
boolean valid;
do {
valid = true;
System.out.print("How many numbers?: ");
try {
n = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.println("Wrong input. Try again.");
valid = false;
}
} while (!valid);
int sum = 0, currentNumber;
for (int i = 1; i <= n; i++) {
do {
valid = true;
System.out.print("Enter an integer: ");
try {
currentNumber = Integer.parseInt(scanner.nextLine());
sum = sum + currentNumber;
} catch (NumberFormatException e) {
System.out.println("Wrong input. Try again.");
valid = false;
}
} while (!valid);
}
System.out.println("Sum: " + sum);
}
}
示例运行:
How many numbers?: 5
Enter an integer: 10
Enter an integer: 20
Enter an integer: 30
Enter an integer: 40
Enter an integer: 50
Sum: 150
另一个示例运行:
How many numbers?:
Wrong input. Try again.
How many numbers?: a
Wrong input. Try again.
How many numbers?: 3
Enter an integer: 10
Enter an integer: a
Wrong input. Try again.
Enter an integer: 15
Enter an integer:
Wrong input. Try again.
Enter an integer: 20
Sum: 45