Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

226
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!