Simplemente no puedo entender por qué recibo una NullPointerException. El programa llega al primer caso y dice i no está apuntando a nada.
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; }Hay varios problemas en su código:
Random ran esté inicializada y esta debería ser la causa raíz de NullPointerExceptionswitch se escribe sin break ni return , por lo tanto, siempre se devolverá "not valid" después de corregir el NPEPosibles soluciones:
switch de Java 12: 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 en una declaración de switch anterior: 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 para reducir la complejidad del código: private static final String PRS = {"paper", "rock", "scissors"}; public String computerChoice() { return PRS[new Random().nextInt(PRS.length)]; }