Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

231
Vistas
How do I pass in the random int into my switch

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;
} 
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Therre are several issues in your code:

  1. It does not show that the Random instance ran is initialized and this should be the root cause of NullPointerException
  2. switch statement is written without break or return, therefore, "not valid" would be always returned after fixing the NPE
  3. Only three valid options should be generated and used in this rock-scissors-stone generator.

Possible fixes:

  1. 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
    }
} 
  1. 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";
    }
} 
  1. 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)];
} 
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda