Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

234
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda