What is the “continue” keyword and how does it work in Java?

前端 未结 13 1785
温柔的废话
温柔的废话 2020-11-22 11:34

I saw this keyword for the first time and I was wondering if someone could explain to me what it does.

  • What is the continue keyword?
  • How
13条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 11:56

    As already mentioned continue will skip processing the code below it and until the end of the loop. Then, you are moved to the loop's condition and run the next iteration if this condition still holds (or if there is a flag, to the denoted loop's condition).

    It must be highlighted that in the case of do - while you are moved to the condition at the bottom after a continue, not at the beginning of the loop.

    This is why a lot of people fail to correctly answer what the following code will generate.

        Random r = new Random();
        Set aSet= new HashSet();
        int anInt;
        do {
            anInt = r.nextInt(10);
            if (anInt % 2 == 0)
                continue;
            System.out.println(anInt);
        } while (aSet.add(anInt));
        System.out.println(aSet);
    

    *If your answer is that aSet will contain odd numbers only 100%... you are wrong!

提交回复
热议问题