什么是numberformatexception?如何修复它?

5cg8jx4n  于 2021-09-13  发布在  Java
关注(0)|答案(9)|浏览(333)
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
x6492ojm

x6492ojm1#

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

换句话说,您试图解析 "Ace of Clubs"int java不能用方法做什么 Integer.parseInt . java提供了漂亮的stacktrace,可以准确地告诉您问题所在。您正在寻找的工具是调试器,使用断点将允许您在所选时刻检查应用程序的状态。
如果要使用解析,解决方案可能是以下逻辑:

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中的异常是什么?

异常是在程序执行期间发生的事件,它会中断程序指令的正常流动。
-文件

整数#parseint中的构造函数和用法

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

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

它们对于理解如何读取堆栈跟踪非常重要。看看这个 NumberFormatException 是从 Integer#parseInt :

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

如果输入的格式 String s 不可解析:

throw NumberFormatException.forInputString(s);

什么是numberformatexception?

抛出以指示应用程序已尝试将字符串转换为其中一种数字类型,但该字符串没有适当的格式。
-文件 NumberFormatException extends IllegalArgumentException . 它告诉我们它更专业 IllegalArgumentException . 事实上,它用于强调尽管参数类型是正确的( String )报告的内容 String 不是数字(a、b、c、d、e、f被认为是十六进制数字,需要时是合法的)。
我怎么修理它?
好吧,不要修正它被抛出的事实。它被扔了真是太好了。您需要考虑以下几点:
我能看一下stacktrace吗?
String 这导致了 Exception A. null ?
它看起来像一个数字吗?
是“我的字符串”还是用户的输入?
待续

公元1年。

消息的第一行是异常发生和输入的信息 String 这导致了问题。字符串总是跟在后面 : 并被引用( "some text" ). 然后,您会对从末尾读取stacktrace感兴趣,因为前几行通常是 NumberFormatException 的构造函数、解析方法等。最后,还有您的方法,您在其中产生了一个bug。将指出它在哪个文件中被调用,在哪个方法中被调用。甚至连一条线都会被连接。你会看到的。上面是如何读取stacktrace的示例。

公元2年。

当你看到的时候,那不是 "For input string:" 而输入,有一个 null (不是 "null" )这意味着,您试图将空引用传递给一个数字。如果你真的想把is当作0或任何其他数字,你可能会对我在stackoverflow上的另一篇文章感兴趣。这里有。
解决意外事件的描述 null s在stackoverflow线程上有很好的描述什么是nullpointerexception,如何修复它?。

公元3年。

如果 String 接下来是 : 在您看来,如果引用的是一个数字,则可能有一个字符您的系统无法解码,或者有一个看不见的空白。明显地 " 6" 无法解析为 "123 " 不能这是因为空间。但有可能发生的是 String 看起来像 "6" 但实际上它的长度比你能看到的数字还要大。
在这种情况下,我建议使用调试器或至少 System.out.println 并打印出 String 您正在尝试解析。如果显示的数字超过位数,请尝试传递 stringToParse.trim() 到解析方法。如果不起作用,请在 : 并使用在线解码器对其进行解码。它会给你所有字符的代码。
还有一个案例是我最近发现的 StackOverflow ,您可能会看到,输入看起来像一个数字。 "1.86" 它只包含这4个字符,但错误仍然存在。记住,只能用#integer#parseint#解析整数。对于解析十进制数,应该使用 Double#parseDouble .
另一种情况是,当数字有许多位数时。可能是因为它太大或太小而无法安装 intlong . 你可能想试试 new BigDecimal(<str>) .

公元4年。

最后,我们达成了一致,当用户以数字字符串形式键入“”时,我们无法避免这种情况。为什么?因为他能。幸运的是,这是因为他是一个测试人员或者只是一个极客。在坏的情况下,是攻击者。
我现在能做什么?java给了我们 try-catch 您可以执行以下操作:

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.
}
bjp0bcyl

bjp0bcyl2#

什么是numberformatexception?

引发此异常是为了指示应用程序已尝试转换 string 到其中一个数字类型,但 string 没有适当的格式。
在您的情况下,根据堆栈跟踪,此异常是由 Integer.parseInt(String) 这意味着 String 不包含可解析的 integer . 仍然根据堆栈跟踪,这是由于您试图解析 String “俱乐部王牌”是一个整数,它不能工作,因为它不是 String 整数的表示法。

如何修复它?

最简单和通用的方法是捕获异常 NumberFormatException ```
int value = -1;
try {
value = Integer.parseInt(myString);
} catch (NumberFormatException e) {
// The format was incorrect
}

它可以工作,但捕获异常的速度很慢,因为它需要构建调用堆栈来创建异常 `Exception` 这是昂贵的,所以如果你可以避免它做它。此外,您还需要适当地管理异常,这并不总是显而易见的。
或者你可以用一个 `regular expression` 首先检查
String `matches` 带着 `Integer` 但它很容易出错,因为您很容易使用错误的 `regular expression` .
在您的情况下,应该使用更面向对象的方法,而不是处理 `String` ,例如,您可以使用 `class` 或 `enum` 表示您的卡,而不是使用简单的 `String` 因为正如您已经注意到的,它更容易出错。
因此,如果您决定为您的卡使用专用类,您的代码可能是:

public class Card {

private final Rank rank;
private final Suit suit;

public Card(final Rank rank, final Suit suit) {
    this.rank = rank;
    this.suit = suit;
}

public Rank getRank() {
    return this.rank;
}

public Suit getSuit() {
    return this.suit;
}

}

对于一张牌的花色和等级,我们可以使用 `enum` 因为现有的军衔和官司数量有限。

public enum Rank {
ACE(1), TWO(2), THREE(3), FOUR(4), FIVE(5), SIX(6), SEVEN(7), HEIGHT(8),
NINE(9), TEN(10), JACK(11), QUEEN(12), KING(13);

private final int value;

Rank(final int value) {
    this.value = value;
}

public int getValue() {
    return this.value;
}

}

public enum Suit {
SPADE, HEART, DIAMOND, CLUB
}

然后 `cards` 将是一系列 `Card` 而不是一个数组 `String` ,并可初始化为下一个:

Rank[] ranks = Rank.values();
Suit[] suits = Suit.values();
Card[] cards = new Card[ranks.length * suits.length];
for (int i = 0; i < ranks.length; i++) {
for (int j = 0; j < suits.length; j++) {
cards[i * suits.length + j] = new Card(ranks[i], suits[j]);
}
}

如果你需要洗牌你的牌阵,你可以继续下一步(请注意,如果你决定使用 `List` 只需使用 `Collections.shuffle(list)` )

List allCards = Arrays.asList(cards);
Collections.shuffle(allCards);
allCards.toArray(cards);

然后,您将能够使用直接访问您的卡的价值 `cards[index].getRank().getValue()` 不冒风险获得例外情况(例外情况除外) `IndexOutOfBoundsException` 如果您没有使用正确的索引)。
fsi0uk1n

fsi0uk1n3#

看起来像 cards[] 是字符串数组,您正在尝试转换 Ace of Clubs 到整数。

int first_value = Integer.parseInt(cards[index]);
wtlkbnrh

wtlkbnrh4#

java.lang.NumberFormatException

当您试图分析某些不是数字字符串的输入时发生。
在您的例子中,您试图将字符串(没有数字)解析为整数。由于不可能,发生numberformatexception异常。

int first_value = Integer.parseInt(cards[index]);//cards[index] value should be //number string "123" not "abc"
nc1teljy

nc1teljy5#

numberformatexception是java告诉您“我试图将字符串转换为int,但我做不到”的方式。
在异常跟踪中,您可以读取

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)

基本上,这意味着在代码的第68行调用integer.parseint方法,将“俱乐部ace”作为参数传递。该方法需要一个以字符串表示的整数值,例如“4”,因此该方法抱怨抛出numberformatexception,因为“俱乐部王牌”看起来根本不是整数。

nvbavucw

nvbavucw6#

A. NumberFormatException 意味着 Integer.parseInt() 无法将字符串转换为数字。
我建议两种选择之一:
将卡片封装为名称(字符串)/值(整数)组合。使用值进行比较,使用名称向用户显示信息。 Cards[] 然后变成一张卡片列表,而不是字符串。
自己解析字符串。这可能更容易,因为您已经用 if(cards[index].startsWith("Ace")) { value = 1; } 位。您可以将它们移动到一个名为 CardToInt() (或其他),并使用该函数而不是 Integer.parseInt() .

0dxa2lsx

0dxa2lsx7#

第一件让我感到困惑的事(没有双关语的意思)是,当值需要为0-52时,你将值限制在1-13。同样,根据你的逻辑,值总是更高。更好的方法是使用数字生成器。下面是我使用数字生成器(或java random)的代码:

public static void main(String[] args) {

String[] cards = { "Ace of Clubs", "1 of Clubs", "2 of Clubs",
        "3 of Clubs", "4 of Clubs", "5 of Clubs", "6 of Clubs",
        "7 of Clubs", "8 of Clubs", "9 of Clubs", "10 of Clubs",
        "Queen of Clubs", "King of Clubs", "Ace of Diamonds",
        "1 of Diamonds", "2 of Diamonds", "3 of Diamonds",
        "4 of Diamonds", "5 of Diamonds", "6 of Diamonds",
        "7 of Diamonds", "8 of Diamonds", "9 of Diamonds",
        "10 of Diamonds", "Queen of Diamonds", "King of Diamonds",
        "Ace of Hearts", "1 of Hearts", "2 of Hearts", "3 of Hearts",
        "4 of Hearts", "5 of Hearts", "6 of Hearts", "7 of Hearts",
        "8 of Hearts", "9 of Hearts", "10 of Hearts",
        "Queen of Hearts", "King of Hearts", "Ace of Spades",
        "1 of Spades", "2 of Spades", "3 of Spades", "4 of Spades",
        "5 of Spades", "6 of Spades", "7 of Spades", "8 of Spades",
        "9 of Spades", "10 of Spades", "Queen of Spades",
        "King of Spades" };

Scanner scanner = new Scanner(System.in);
Random rand = new Random();
String response = "";
int index = 0;
int value = 0;  
while (!response.equals("q") && index < 52) {

    // set next card value based on current set of cards in play
    if (cards[index].endsWith("Clubs")) {
        value = rand.nextInt(12);
    }
    if (cards[index].endsWith("Diamonds")) {
        value = rand.nextInt(12) + 13;
    }
    if (cards[index].endsWith("Hearts")) {
        value = rand.nextInt(12) + 26;
    }
    if (cards[index].endsWith("Spades")) {
        value = rand.nextInt(12) + 39;
    }

    // display card too user (NOTE: we use the random number not the index)
    System.out.println("Card is: " + cards[value]);

    // ask user what well the next card be
    System.out.println("Will the next card be higher or lower?, press q if you want to quit");
    response = scanner.nextLine();

    // display if user was right (NOTE: compared the random number to the current index)
    // ignore incorrect response and just continue
    if ((value > index && response.startsWith("h")) || (value < index && response.startsWith("l"))) {
        System.out.println("You answer was right, well done!");
    } else {
        System.out.println("You answer was wrong, try again!");
    }

    // continue loop
    index++;
}
}

至于数字形式概念,我相信尼古拉斯·菲洛托解释得很好。

n7taea2i

n7taea2i8#

int first_value = Integer.parseInt(cards[index]);

在编写上述语句时,您试图将“俱乐部王牌”解析为一个数字。
您可以使用以下方法测试是否可以将任何字符串解析为整数:

boolean tryParseInt(String value) {  
     try {  
         Integer.parseInt(value);  
         return true;  
      } catch (NumberFormatException e) {  
         return false;  
      }  
}

关于您的问题,什么是numberformatexception:抛出它是为了指示应用程序试图将字符串转换为一种数值类型,但该字符串没有适当的格式(参考号-http://docs.oracle.com/javase/7/docs/api/java/lang/numberformatexception.html)

4uqofj5v

4uqofj5v9#

代码中会出现异常,将字符串转换为整数:

int first_value = Integer.parseInt(cards[index]);

其中,您将字符串作为“俱乐部王牌”传递,该字符串不可能转换为整数,因此它会引发数字格式异常。你可以用,

try {
     ....
     // Your Code
     ....
    }
catch(NumberFormatException e)
{
    e.getMessage();  //You can use anyone like printStackTrace() ,getMessage() to handle the Exception
}

相关问题