stringRounds正在循环,拒绝有效值



当我输入无效值时,循环正在工作,但当我输入有效值时,它仍然显示相同的消息。请帮忙。

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!!"));
}
}

因为您没有在while循环中更新舍入值。

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!!"));
}

在while循环中对rounds设置条件,但不修改其值。

此外,您应该在需要时声明新的Random((,我建议您使用Random.nextInt(n(,因为它不太可预测。

最后,为什么要使用字符串作为用户选择?你需要解析它。。。您应该使用int。

最新更新