Java 什么是NumberFormatException?如何修复它?

Java 什么是NumberFormatException?如何修复它?,java,arrays,while-loop,numberformatexception,Java,Arrays,While Loop,Numberformatexception,我的While循环: 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

我的While循环:

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(响应!=“q”&&index<52){
系统输出打印项次(卡片[索引]);
int first_value=Integer.parseInt(卡片[索引]);
int值=0;
//添加扫描仪
扫描仪=新的扫描仪(System.in);
System.out.println(“下一张卡是更高还是更低?如果要退出,请按q”);
字符串猜测=scanner.nextLine();
if(cards[index].startsWith(“Ace”){value=1;}
if(cards[index].startsWith(“2”){value=2;}
if(cards[index].startsWith(“3”){value=3;}
//检查4-10
if(cards[index].startsWith(“Queen”){value=11;}
if(cards[index].startsWith(“King”){value=12;}
if(猜一猜,从(“h”)开始){
if(value>first_value){System.out.println(“您的答案是对的,weldone!”);}
else{System.out.println(“您的答案错了,再试一次!”);}
}else if(猜一猜,从(“l”)开始){
如果(value
看起来像是
卡片[]
字符串数组,您正在尝试将
俱乐部王牌
转换为整数

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
换句话说,您试图将
“俱乐部王牌”
解析为
int
Java无法使用方法
Integer.parseInt
。Java提供了漂亮的stacktrace,可以准确地告诉您问题所在。您正在寻找的工具是调试器,使用断点将允许您在所选时刻检查应用程序的状态

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

Java中的
异常是什么?
异常是一个事件,它发生在 程序,它会中断程序指令的正常流程

-

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

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

public NumberFormatException (String s) {
    super (s);
}
如果输入
字符串s
的格式不可解析,则为:

if (s == null) {
    throw new NumberFormatException("null");
}
什么是
NumberFormatException
抛出以指示应用程序已尝试将字符串转换为其中一种数字类型,但该字符串没有适当的格式

-

NumberFormatException
扩展了
非法argumentexception
。它告诉我们它更专业化
IllegalArgumentException
。事实上,它用于强调,尽管参数类型是正确的(
String
),但
字符串的内容不是数字(a、b、c、d、e、f被认为是十六进制数字,需要时是合法的)

如何修复它?
好吧,不要修正它被抛出的事实。它被扔了真是太好了。您需要考虑以下几点:

  • 我能看一下stacktrace吗
  • 导致
    异常的
    字符串是否为
    null
  • 它看起来像一个数字吗
  • 是“我的字符串”还是用户的输入
  • 待续
  • 广告1. 消息的第一行是发生异常的信息和导致问题的输入字符串。字符串始终紧跟在
    之后并被引用(
    “某些文本”
    )。然后,您开始对从末尾读取stacktrace感兴趣,因为前几行通常是
    NumberFormatException
    的构造函数、解析方法等。最后,您的方法中出现了一个bug。将指出它在哪个文件中被调用,在哪个方法中被调用。甚至连一条线都会被连接。你会看到的。上面是如何读取stacktrace的示例

    广告2. 当您看到输入字符串:“
    和输入时,出现了一个
    null
    (不是
    “null”
    ),这意味着您试图将null引用传递给一个数字。如果你真的想把is当作0或任何其他数字,你可能会对我在StackOverflow上的另一篇文章感兴趣。有空

    StackOverflow线程中详细描述了如何解决意外的
    null
    s

    广告3. 如果您认为
    后面引用的
    字符串类似于一个数字,则可能存在您的系统无法解码的字符或不可见的空白。显然,
    “6”
    不能被解析,
    “123”
    也不能被解析。这是因为空间。但是可能会出现这样的情况,
    字符串
    看起来像
    “6”
    ,但实际上它的长度将大于您可以看到的位数

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

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

    另一种情况是,当数字有许多位数时。可能是,
    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
        }
    }
    
    static NumberFormatException forInputString(String s) {
        return new NumberFormatException("For input string: \"" + s + "\"");
    }
    
    public NumberFormatException (String s) {
        super (s);
    }
    
    if (s == null) {
        throw new NumberFormatException("null");
    }
    
    throw NumberFormatException.forInputString(s); 
    
    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.
    }
    
    int value = -1;
    try {
        value = Integer.parseInt(myString);
    } catch (NumberFormatException e) {
        // The format was incorrect
    }
    
    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;
        }
    }
    
    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
    }
    
    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<Card> allCards = Arrays.asList(cards);
    Collections.shuffle(allCards);
    allCards.toArray(cards);
    
    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++;
    }
    }
    
    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
    }
    
    java.lang.NumberFormatException 
    
    int first_value = Integer.parseInt(cards[index]);//cards[index] value should be //number string "123" not "abc"
    
    int first_value = Integer.parseInt(cards[index]); 
    
    boolean tryParseInt(String value) {  
         try {  
             Integer.parseInt(value);  
             return true;  
          } catch (NumberFormatException e) {  
             return false;  
          }  
    }
    
    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)