I just can't figure out why I'm getting a NullPointerException. The program gets to the first case and says i is not pointing to anything.
public String computerChoice()
{
int i = ran.nextInt(4);
String str;
switch (i){
case 1:
str = "paper";
case 2:
str = "rock";
case 3:
str = "scissors";
default:
str = "not valid";
}
return str;
}
Therre are several issues in your code:
Random instance ran is initialized and this should be the root cause of NullPointerExceptionswitch statement is written without break or return, therefore, "not valid" would be always returned after fixing the NPEPossible fixes:
switch expression syntax:
public String computerChoice() {
return switch (new Random().nextInt(3)) { // values in range [0..2]
case 0 -> "paper";
case 1 -> "rock";
default -> "scissors"; // the only remaining value 2 should be default
}
}
return in older switch statement:public String computerChoice() {
switch (new Random().nextInt(3)) { // values in range [0..2]
case 0: return "paper";
case 1: return "rock";
default: return "scissors";
}
}
switch at all to reduce the code complexity:private static final String PRS = {"paper", "rock", "scissors"};
public String computerChoice() {
return PRS[new Random().nextInt(PRS.length)];
}