Issue
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!!"));
}
}
Solution
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!!"));
}
Answered By - Zinedine Benkhider
Answer Checked By - Willingham (JavaFixing Volunteer)