简体   繁体   English

Java - 两个同时循环不能与扫描仪一起工作

[英]Java - two do while Loops not working with scanner

import java.util.Scanner;

public class doWhileLoops 
{
    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Guess a number between 1 and 10:");
        int val = input.nextInt();

        do
        {
            System.out.println("Guess Again!");
            val = input.nextInt();
        }
        while(val != 5);

        do
        {
            System.out.println("Stop messing around!");
            val = input.nextInt();
        }
        while(val < 1 || val > 10);

        if(val == 5)
        {
            System.out.println("Nice guess!");
        }
    }
}

I am not sure what is wrong with this code, I have tried to change it many ways but it just does not run how i want it to.我不确定这段代码有什么问题,我尝试了很多方法来改变它,但它只是没有按照我想要的方式运行。 If the user enters anything but 5 then it says "guess again", even if it is over 10 or less than 1, but until the user enters 5, does it say "stop messing around!", then if I enter 5 again, then it says "Nice guess".如果用户输入除 5 以外的任何内容,那么它会说“再猜一次”,即使它超过 10 或小于 1,但直到用户输入 5,它是否会说“停止乱搞!”,那么如果我再次输入 5,然后它说“很好的猜测”。

使用 do-while 语句,您执行 do 块中的代码一次,然后验证 while 语句中的条件,因此如果您不想在验证之前执行一次,我建议您使用 while 而不是 do-while。

maybe something like也许像

........ …………

 while(val != 5){
        System.out.println("Guess Again!");
        val = input.nextInt();

         if(val < 1 || val > 10){
                 System.out.println("Stop messing around!");
                 val = input.nextInt();
         }
    }


    if(val == 5)
    {
        System.out.println("Nice guess!");
    }

...... ......

will do the expected result.会做预期的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM