The loop is working when I enter invalid values, but it still shows the same message when I enter a Valid value. Please help.
public class RockPaperScissors {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random rnd = new Random();
String stringRounds = " ";
System.out.println("Welcome to Rock, Paper Scissors!");
System.out.println("Let's begin with the number of rounds you would like to play: " );
stringRounds = sc.nextLine();
int rounds = Integer.parseInt(stringRounds);
while (rounds < 1 || rounds > 10) {
System.out.println(stringRounds (" is out of my range. Please try again."));
stringRounds = sc.nextLine();
}
System.out.println(stringRounds (" sounds good to me. Let's Get Started!!"));
}
}
CodePudding user response:
Because you don't update the value of rounds in the while loop.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random rnd = new Random();
String stringRounds = " ";
System.out.println("Welcome to Rock, Paper Scissors!");
System.out.println("Let's begin with the number of rounds you would like to play: " );
stringRounds = sc.nextLine();
int rounds = Integer.parseInt(stringRounds);
while (rounds < 1 || rounds > 10) {
System.out.println(stringRounds (" is out of my range. Please try again."));
stringRounds = sc.nextLine();
rounds= Integer.parseInt(stringRounds);//add this row
}
System.out.println(stringRounds (" sounds good to me. Let's Get Started!!"));
}
CodePudding user response:
You make a condition on rounds
in the while loop, but you do not modify its value.
Also, you should declare your new Random() when you need it, and I suggest you to use Random.nextInt(n) instead, it's less predictable.
Last thing, why use a String for the user choice ? You need to parse it ... You should use int instead.