Therre are several issues in your code:
- It does not show that the
Random instance ran is initialized and this should be the root cause of NullPointerException
switch statement is written without break or return, therefore, "not valid" would be always returned after fixing the NPE
- Only three valid options should be generated and used in this rock-scissors-stone generator.
Possible fixes:
- Use Java 12
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
}
}
- Use
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";
}
}
- Create and use an array of possible values without any
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)];
}