Reputation: 11251
I make chessboard, where alone king will walk according to the rules of chess. Below it's method to make, it called for 2 times for i and j coordinate of King, I Made input variable String to check if this King's coordinates already exist. Than I try to convert it to integer, seems something wrong with this conversion.
import java.util.*;
public class King {
int move(String iK){
Random rand = new Random();
Integer coordinateKing = Integer.valueOf(iK);
if (iK == null){
coordinateKing = rand.nextInt(8);
}else{
int caseI;
switch(caseI = rand.nextInt(2)){
case 0: if (coordinateKing < 8){ coordinateKing++; } else {caseI = rand.nextInt(2);}
break;
case 1: if (coordinateKing > 0){ coordinateKing--; } else {caseI = rand.nextInt(2);}
break;
default:
break;
}
}
return coordinateKing;
}
}
I have problem like this:
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:454)
at java.lang.Integer.valueOf(Integer.java:582)
at chess_engine.King.move(King.java:6)
at chess_engine.MainClass.main(MainClass.java:12)
Thanks in advance!
Upvotes: 0
Views: 384
Reputation: 7324
It is a runtime error: here the iK is receiving a null value and an Integer object can store null but the method valueOf()
internally uses the parseInt()
method which returns an int value and a null cannot be converted to int
Upvotes: 1
Reputation: 405765
You're attempting to convert iK
to an integer before you check to see if it's null
. This line is where the exception is thrown:
Integer coordinateKing = Integer.valueOf(iK);
But you check if (iK == null)
on the line following that. You should do a null
test first. You can fix this by declaring coordinateKing
before your if
statement and setting its value in the if...else
blocks.
Integer coordinateKing = 0;
if (iK == null){
coordinateKing = rand.nextInt(8);
} else {
coordinateKing = Integer.valueOf(iK);
int caseI;
...
}
Upvotes: 2
Reputation: 64399
You call this
Integer coordinateKing = Integer.valueOf(iK);
but iK
can be NULL there. do your null check first
Upvotes: 2
Reputation: 42176
The exception is pretty self-explanatory. iK is a null String, which can't be converted to an Integer. What Integer do you want when iK is null?
Upvotes: 1