What is a NumberFormatException and how can I fix it?

前端 未结 9 1348
渐次进展
渐次进展 2020-11-21 04:25
Error Message:
Exception in thread \"main\" java.lang.NumberFormatException: For input string: \"Ace of Clubs\"
    at java.lang.NumberFormatException.forInputString         


        
相关标签:
9条回答
  • 2020-11-21 05:01

    A NumberFormatException means that Integer.parseInt() couldn't translate the string into a number.

    I would suggest one of two options:

    1. Encapsulate cards as a name(string)/value(int) combo. Use the value to do comparisons, and the name to present info to the user. Cards[] then becomes a list of cards, not strings.

    2. Parse the strings yourself. Which may be easier, since you've already done it with the if(cards[index].startsWith("Ace")) { value = 1; } bits. You can move those into a function called CardToInt() (or whatever), and use that function instead of Integer.parseInt().

    0 讨论(0)
  • 2020-11-21 05:04

    Looks like cards[] is String array and you are trying to convert Ace of Clubs to Integer.

    int first_value = Integer.parseInt(cards[index]);
    
    0 讨论(0)
  • 2020-11-21 05:05
    java.lang.NumberFormatException 
    

    occurs when you are trying to parse some input which not a Number string.

    In your case your trying to parse a string (which not has number )as Integer. As its not possible NumberFormatException exception occured.

    int first_value = Integer.parseInt(cards[index]);//cards[index] value should be //number string "123" not "abc"
    
    0 讨论(0)
提交回复
热议问题