Question

I'm having an odd problem here. Not sure what the cause is. I'm writing in Java for a speech demonstration, and I'm writing a few simple programs. For some reason, it doesn't always want to return my random number when working with a rock paper scissors program. My starting code is below, and I want to say that one out of every 3 times, it'll actually print out a number.

Random rand = new Random();
int randomNum = rand.nextInt(3) + 1;
System.out.println(randomNum);

Like I said, very simple code, but I have no clue as to why it is only sometimes printing out numbers...

Edit: Entire Project

Main import java.util.Scanner;

public class Speech_Main {

public static void main(String[] args) {
        boolean running = true;
        Scanner in = new Scanner(System.in);


        while(running){
            if(in.next().equalsIgnoreCase("exit")){
                running = false;
            }
            if(in.next().equalsIgnoreCase("Hello_World")){
                Hello_World.start();
            }
            if(in.next().equalsIgnoreCase("rps")){
                Rock_Paper_Scissors.start();
            }
        }
        in.close();
        return;
}

}

RPS

import java.util.Random;


public class Rock_Paper_Scissors {
public static void start(){
    System.out.println(random());
}
private static int random(){

    Random rand = new Random();
    int randomNum = rand.nextInt() + 1;
    return randomNum;
}
}
Was it helpful?

Solution

The problem is that each time in your loop, you call in.next() three times:

    while(running){
        if(in.next().equalsIgnoreCase("exit")){
            running = false;
        }
        if(in.next().equalsIgnoreCase("Hello_World")){
            Hello_World.start();
        }
        if(in.next().equalsIgnoreCase("rps")){
            Rock_Paper_Scissors.start();
        }
    }

When you get to the first if, you call in.next(), which gets the next token from the scanner. The problem is that when you get to the second if, it will call in.next() again, which will then try to get another token. It doesn't use the previous one, because you've told it to get a new one. To fix this, declare a variable to hold in.next() at the beginning of the loop:

String input = in.next();

and then check the variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top