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)
My While Loop:
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
java.lang.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.
It's pretty much common sense like a null cannot be converted to a number so you will NumberFormatException. The same is true for an empty String or a non-numeric String.
The NumberFormatException is a built-in class in java that is defined in the Java. lang. NumberFormatException package. The IllegalArgumentException class is a superclass of the NumberFormatException as it is an unchecked exception, so it is not forced to handle and declare it.
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
means:
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
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 } }
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.
-Documentation
Integer#parseInt
static NumberFormatException forInputString(String s) { return new NumberFormatException("For input string: \"" + s + "\""); } public NumberFormatException (String s) { super (s); }
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"); }
or later if the format of the input String s
is not parsable:
throw NumberFormatException.forInputString(s);
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.
-Documentation
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:
String
which causes an Exception
a null
?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.
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.
The description of solving unexpected null
s is well described on StackOverflow thread What is a NullPointerException and how can I fix it?.
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.
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.
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
.
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>)
.
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.
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
?This exception is thrown to indicate that the application has attempted to convert a
string
to one of the numeric types, but that thestring
does not have the appropriate format.
In your case, according to your stack trace this exception was thrown by Integer.parseInt(String)
which means that the provided String
does not contain a parseable integer
. And still according to the stack trace, it is due to the fact that you tried to parse the String
"Ace of Clubs" as an integer which cannot work as it is not the String
representation of an integer.
The simplest and generic way is to catch the exception NumberFormatException
int value = -1;
try {
value = Integer.parseInt(myString);
} catch (NumberFormatException e) {
// The format was incorrect
}
It will work but catching an exception is slow because it needs to build the call stack to create the Exception
which is costly, so if you can avoid it do it. Moreover you will need to manage the exception properly which is not always obvious.
Or you could use a regular expression
to check first if the String
matches
with an Integer
but it is quite error prone as you could easily use a wrong regular expression
.
In your case, a more OO approach should be used instead of dealing with String
, for example you could use a class
or an enum
to represent your cards instead of using simple String
because it is much more error prone as you have already noticed.
So if you decide to use a dedicated class for your card, your code could be:
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;
}
}
For the suit and the rank of a card, we can use an enum
since there are limited amounts of existing ranks and suits.
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
}
Then cards
would be an array of Card
instead of an array of String
, and could be initialized as next:
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]);
}
}
If you need to shuffle your array of cards, you can proceed as next (please note that if you decide to use a List
of cards instead of an array simply use Collections.shuffle(list)
)
List<Card> allCards = Arrays.asList(cards);
Collections.shuffle(allCards);
allCards.toArray(cards);
Then you will be able to access directly to the value of your card with cards[index].getRank().getValue()
without taking the risk to get an exception (except an IndexOutOfBoundsException
if you don't use a proper index).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With