简单的java - 做while while循环

时间:2016-11-30 11:55:57

标签: java do-while

嗨我有关于while while循环的问题。我是一个初学者,所以我猜这是一个非常简单的问题。

我有这个程序:

public class MyClass {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int value = 0;
        do {
            System.out.println("Enter a number");
            value = input.nextInt();
        }

        while (value != 5);
        {

            System.out.println("Got 5!");
        }
    }
}

哪个转弯产生得到5!当输入为5时,它可以正常工作。我的问题是,为什么不“得到5!”当值输入不是5时执行,因为条件表示“值!= 5”并且Sysout在该条件内。执行条件不一定是真的吗?

我从教程中得到了这个例子并且没有自己写出来这就是为什么我有点困惑。

3 个答案:

答案 0 :(得分:10)

do-whileSystem.out.println("Got 5!");循环的条件。只要值!= 5,该循环永远不会终止,并且您永远不会到达Scanner input = new Scanner(System.in); int value = 0; do { System.out.println("Enter a number"); value = input.nextInt(); } while (value != 5); System.out.println("Got 5!"); 行。

如果您重新安排代码,也许会更清楚:

System.out.println
  

条件状态"值!= 5"而Sysout就是在这种情况下。

不,value != 5不在条件范围内。

System.out.println("Got 5!");条件没有以任何方式连接到包含var sectionOption = ""; var $sectionSelect = $('#modal_cmbSection'); $sectionSelect.empty(); $(".section-block").each(function() { var eachSectionName = $(this).find(".section-section-name").val(); sectionOption = "<option>" + eachSectionName + "</option>"; $sectionSelect.append(sectionOption); }); //set selected as true for first option $("#modal_cmbSection option:first-child").attr("selected", true); 语句的块,这就是为什么我删除了该块的大括号。

答案 1 :(得分:1)

Java并不关心空行,但人类却如此。请允许我重写代码,以便更清楚:

do {
    System.out.println("Enter a number");
    value = input.nextInt();
}
while (value != 5);

{
    System.out.println("Got 5!");
}

甚至(没有理由将print语句放在自己的块中):

do {
    System.out.println("Enter a number");
    value = input.nextInt();
} while (value != 5);

System.out.println("Got 5!");

现在更容易注意到&#39; while&#39; keword及其谓词是do-while复合语句的一部分,与print语句无关。 do-while内的代码一次又一次地执行,直到条件为假。只有这样才能执行以下代码。

答案 2 :(得分:0)

请阅读Do-while loop

的语法
public static void main(String[] args)
{
    Scanner input = new Scanner(System.in);

    int value = 0;
    do {
        System.out.println("Enter a number");
        value = input.nextInt();
    } while (value != 5); // This do-while loop exits if input is 5.

    // The below code is a normal block of code, which is executed
    // without any condition, only after execution of above loop
    // completes.
    {
        System.out.println("Got 5!");
    }
}
相关问题