什么是NumberFormatException以及如何解决? [英] What is a NumberFormatException and how can I fix it?

查看:3716
本文介绍了什么是NumberFormatException以及如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Error Message:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Ace of Clubs"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at set07102.Cards.main(Cards.java:68)
C:\Users\qasim\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)

我的While循环:

while (response != 'q' && index < 52) {
    System.out.println(cards[index]);
    int first_value = Integer.parseInt(cards[index]);
    int value = 0;
    //Add a Scanner
    Scanner scanner = new Scanner(System.in);
    System.out.println("Will the next card be higher or lower?, press q if you want to quit");
    String guess = scanner.nextLine();
    if(cards[index].startsWith("Ace")) { value = 1; }
    if(cards[index].startsWith("2")) { value = 2; }
    if(cards[index].startsWith("3")) { value = 3; }
    //checking 4-10
    if(cards[index].startsWith("Queen")){ value = 11; }
    if(cards[index].startsWith("King")){ value = 12; }
    if(guess.startsWith("h")){
        if(value > first_value){ System.out.println("You answer was right, weldone!"); } 
        else { System.out.println("You answer was wrong, try again!"); }
    } else if(guess.startsWith("l")){
        if(value < first_value) { System.out.println("You answer as right, try again!"); }
        else { System.out.println("You answer was wrong, try again!"); }
    } else { System.out.println("Your was not valid, try again!"); }
    scanner.close();            
    index++;
}//end of while loop


推荐答案

Error Message:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Ace of Clubs"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at set07102.Cards.main(Cards.java:68)
C:\Users\qasim\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1

表示:

There was an error. We try to give you as much information as possible
It was an Exception in main thread. It's called NumberFormatException and has occurred for input "Ace of Clubs".
at line 65th of NumberFormatException.java which is a constructor,
which was invoked from Integer.parseInt() which is in file Integer.java in line 580,
which was invoked from Integer.parseInt() which is in file Integer.java in line 615,
which was invoked from method main in file Cards.java in line 68.

It has resulted in exit code 1

换句话说,你试图解析俱乐部的王牌 int Java不能用方法 Integer.parseInt 。 Java提供了漂亮的堆栈跟踪,它可以准确地告诉您问题所在。您正在寻找的工具是调试器,使用断点将允许您在所选时刻检查应用程序的状态

In other words, you tried to parse "Ace of Clubs" to an int what Java can't do with method Integer.parseInt. Java has provided beautiful stacktrace which tells you exactly what the problem is. The tool you're looking for is debugger and using breakpoints will allow you to inspect the state of you application at the chosen moment.

如果你想使用解析,解决方案可能是以下逻辑:

The solution might be the following logic in case you want to use parsing:

if (cards[index].startsWith("Ace")) 
    value = 1;
else if (cards[index].startsWith("King"))
    value = 12;
else if (cards[index].startsWith("Queen"))
    value = 11;
...
else {
    try {
        Integer.parseInt(string.substring(0, cards[index].indexOf(" "))); 
    } catch (NumberFormatException e){
        //something went wrong
    }
}



Java中的异常是什么?



What is an Exception in Java?


异常是在执行
程序期间发生的事件,它会破坏程序指令的正常流程。

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

- 文档

static NumberFormatException forInputString(String s) {
    return new NumberFormatException("For input string: \"" + s + "\"");
}

public NumberFormatException (String s) {
    super (s);
}

它们对于理解如何读取堆栈跟踪非常重要。看看如何从整数#parseInt 抛出 NumberFormatException

They are important for understanding how to read the stacktrace. Look how the NumberFormatException is thrown from Integer#parseInt:

if (s == null) {
    throw new NumberFormatException("null");
}

或更高版本如果输入格式 String s 无法解析:

or later if the format of the input String s is not parsable:

throw NumberFormatException.forInputString(s); 



什么是 NumberFormatException



What is a NumberFormatException?


抛出以指示应用程序已尝试将字符串转换为其中一种数字类型,但字符串确实没有适当的格式。

Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.

- 文档

NumberFormatException extends IllegalArgumentException 。它告诉我们它更专业 IllegalArgumentException 。实际上,它用于突出显示虽然参数类型是正确的( String ),但 String 的内容是' t numeric( a,b,c,d,e,f在HEX中被视为数字,在需要时是合法的)。

NumberFormatException extends IllegalArgumentException. It tells us that it's more specialized IllegalArgumentException. Indeed, it's used for highlighting that although, the argument type was correct (String) the content of the String wasn't numeric (a,b,c,d,e,f are considered digits in HEX and are legal when needed).

我该如何修复它?

好​​吧,不要修复它抛出的事实。扔掉它真好。有些事情你需要考虑:

How do I fix it?
Well, don't fix the fact that it's thrown. It's good that it's thrown. There are some things you need to consider:


  1. 我可以阅读堆栈跟踪吗?

  2. String 导致异常 a null

  3. 它看起来像一个数字吗?

  4. 是'我的字符串'还是用户的输入?

  5. 待续

  1. Can I read the stacktrace?
  2. Is the String which causes an Exception a null?
  3. Does it look like a number?
  4. Is it 'my string' or user's input?
  5. to be continued



广告。 1。



消息的第一行是发生异常的信息,输入是 String 导致了这个问题。字符串始终遵循并被引用(some text)。然后你有兴趣从最后读取堆栈跟踪,因为前几行通常是 NumberFormatException 的构造函数,解析方法等。然后在最后,有你的方法你犯了一个bug。将在其调用的文件和方法中指出。即使是一条线也会被附加。你会看到的。上面是如何阅读堆栈跟踪的示例。

Ad. 1.

The first line of a message is an information that the Exception occurred and the input String which caused the problem. The String always follows : and is quoted ("some text"). Then you become interested in reading the stacktrace from the end, as the first few lines are usually NumberFormatException's constructor, parsing method etc. Then at the end, there is your method in which you made a bug. It will be pointed out in which file it was called and in which method. Even a line will be attached. You'll see. The example of how to read the stacktrace is above.

当你看到,而不是输入字符串:和输入,有一个 null 不是null )这意味着,你尝试过将空引用传递给数字。如果你真的想要对待0或任何其他数字,你可能会对我在StackOverflow上的另一篇文章感兴趣。 此处可用。

When you see, that instead of "For input string:" and the input, there is a null (not "null") it means, that you tried to pass the null reference to a number. If you actually want to treat is as 0 or any other number, you might be interested in my another post on StackOverflow. It's available here.

解决意外情况<$的说明c $ c> null s在StackOverflow线程上有详细描述 什么是NullPointerException,我该怎么办?修复它?

The description of solving unexpected nulls is well described on StackOverflow thread What is a NullPointerException and how can I fix it?.

如果后面的 String 和引用看起来像你认为的数字,可能有一个你的系统无法解码的字符或一个看不见的空格。显然6无法解析,123也无法解析。这是因为空间。但它可能会发生, String 看起来像6但实际上它的长度将大于数字您可以看到的数字。

If the String that follows the : and is quoted looks like a number in your opinion, there might be a character which your system don't decode or an unseen white space. Obviously " 6" can't be parsed as well as "123 " can't. It's because of the spaces. But it can occure, that the String will look like "6" but actually it's length will be larger than the number of digits you can see.

在这种情况下,我建议使用调试器或至少 System.out.println 并打印您尝试解析的 String 的长度。如果它显示的位数超过了位数,请尝试将 stringToParse.trim()传递给解析方法。如果它不起作用,请在之后复制整个字符串,并使用在线解码器对其进行解码。它会给你所有字符的代码。

In this case I suggest using the debugger or at least System.out.println and print the length of the String you're trying to parse. If it shows more than the number of digits, try passing stringToParse.trim() to the parsing method. If it won't work, copy the whole string after the : and decode it using online decoder. It'll give you codes of all characters.

最近我发现了一个案例 StackOverflow ,你可能会看到,输入看起来像一个数字,例如1.86并且它只包含这4个字符,但错误仍然存​​在。请记住,只能用#Integer#parseInt#解析整数。对于解析十进制数字,应使用 Double#parseDouble

There is also one case which I have found recently on StackOverflow, that you might see, that the input looks like a number e.g. "1.86" and it only contains those 4 characters but the error still exists. Remember, one can only parse integers with #Integer#parseInt#. For parsing decimal numbers, one should use Double#parseDouble.

另一种情况是,当数字有多位数时。可能是,它太大或太小而不适合 int long 。您可能想尝试新BigDecimal(< str>)

Another situation is, when the number has many digits. It might be, that it's too large or too small to fit int or long. You might want to try new BigDecimal(<str>).

最后,我们来到了我们同意的地方,当用户输入abc作为数字字符串时,我们无法避免这种情况。为什么?因为他可以。幸运的是,这是因为他是测试人员或者只是一个极客。在一个糟糕的情况下,它是攻击者。

Finally we come to the place in which we agree, that we can't avoid situations when it's user typing "abc" as a numeric string. Why? Because he can. In a lucky case, it's because he's a tester or simply a geek. In a bad case it's the attacker.

我现在能做什么?嗯,Java给了我们 try-catch 您可以执行以下操作:

What can I do now? Well, Java gives us try-catch you can do the following:

try {
    i = Integer.parseInt(myString);
} catch (NumberFormatException e) {
    e.printStackTrace();
    //somehow workout the issue with an improper input. It's up to your business logic.
}

这篇关于什么是NumberFormatException以及如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆