netbeans stringRounds是循环的,拒绝有效值

brccelvz  于 2022-11-10  发布在  其他
关注(0)|答案(2)|浏览(133)

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

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

vfhzx4xs1#

因为你没有在while循环中更新rounds的值。

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

vh0rcniy2#

在while循环中对rounds设置条件,但不修改其值。
另外,在需要的时候应该声明新的Random(),我建议您使用Random.nextInt(n),因为它的可预测性较差。
最后一件事,为什么要使用字符串作为用户选择?你需要解析它...你应该用int代替。

相关问题