简体   繁体   English

NumberFormatException:对于输入字符串:“”?

[英]NumberFormatException: For input string: “”?

Code代码

int weight = 0;
do {
    System.out.print("Weight (lb): ");
    weight = Integer.parseInt(console.nextLine());
    if (weight <= 0) {
        throw new IllegalArgumentException("Invalid weight.");
    }
} while (weight <= 0);

Traceback追溯

Weight (lb): Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.base/java.lang.Integer.parseInt(Integer.java:662)
    at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at HealthPlan.main(HealthPlan.java:46)

When I run my program, I get this exception.当我运行我的程序时,我得到了这个异常。 How do I handle it?我该如何处理?

I want to input an integer as a weight value.我想输入一个整数作为weight值。 I also have to use an integer value for height , but my program asks for input that are boolean s and character s as well.我还必须对height使用整数值,但我的程序要求输入也是boolean s 和character s。

Someone suggested that I should use Integer.parseInt .有人建议我应该使用Integer.parseInt

If I need to post more code, I'd be happy to do so.如果我需要发布更多代码,我很乐意这样做。

Sometimes it simply means that you're passing an empty string into Integer.parseInt() :有时它只是意味着您将一个空字符串传递给Integer.parseInt()

String a = "";
int i = Integer.parseInt(a);

You can only cast String into an Integer in this case.在这种情况下,您只能将 String 转换为 Integer。

Integer.parseInt("345")

but not in this case但不是在这种情况下

Integer.parseInt("abc")

This line is giving an exception Integer.parseInt(console.nextLine());这一行给出了一个异常Integer.parseInt(console.nextLine());

Instead, Use this Integer.parseInt(console.nextInt());相反,使用这个Integer.parseInt(console.nextInt());

As I did not see a solution given:因为我没有看到给出的解决方案:

int weight = 0;
do {
    System.out.print("Weight (lb): ");
    String line = console.nextLine();
    if (!line.matches("-?\\d+")) { // Matches 1 or more digits
        weight = -1;
        System.out.println("Invalid weight, not a number: " + line);
    } else {
        weight = Integer.parseInt(line);
        System.out.println("Invalid weight, not positive: " + weight);
    }
} while (weight <= 0);

Integer.parseInt(String) has to be given a valid int. Integer.parseInt(String)必须给出一个有效的 int。

Also possible is:也可能是:

    try {
        weight = Integer.parseInt(line);
    } catch (NumberFormatException e) {
        weight = -1;
    }

This would also help with overflow, entering 9999999999999999.这也将有助于溢出,输入 9999999999999999。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM