简体   繁体   English

(初学者)JAVA do...while 循环逻辑坏了?

[英](BEGINNER) JAVA do...while loop logic broken?

In the code bellow I make a do..while loop that is supposed to repeat if the value is between 1000 and 9999, but the logic of the do..while loop seems off.在下面的代码中,我做了一个 do..while 循环,如果值在 1000 和 9999 之间,它应该重复,但 do..while 循环的逻辑似乎不对。

import java.util.Scanner;
public class Nal2 {
public static void main(String[] ARGS) {
    int i = 0;
    Scanner bralnik = new Scanner(System.in);
    do {
        System.out.printf("Insert a 4 digit num: ");
        i = bralnik.nextInt();
    } while (i >= 1000 && i <= 9999);

    System.out.print("Oi");
  }
}

This dosen't work but the code bellow works.这不起作用,但下面的代码有效。

import java.util.Scanner;
public class Nal2 {
public static void main(String[] ARGS) {
    int i = 0;
    Scanner bralnik = new Scanner(System.in);

    do {
        System.out.printf("Insert a 4 digit num: ");
        i = bralnik.nextInt();

    } while (i <= 1000 || i >= 9999);

    System.out.print("Oi");
 }
}

Shouldn the && works instead of the ||应该&&工作而不是|| ? ?

I'm really confused about this.我真的很困惑。

I'm using InteliJ IDEA 2019.3.4 CE我正在使用 InteliJ IDEA 2019.3.4 CE

   public static void main(String[] args) {
        int i = 0;
        Scanner bralnik = new Scanner(System.in);

        do {
            System.out.printf("Insert a 4 digit num: ");
            i = bralnik.nextInt();


        } while (!(i<=1000||i>=9999));

        System.out.print("Oi");
    }

if you write code just with OR(||), you write above.如果你只用 OR(||) 写代码,你就写在上面。 ! is Logical not Reverse the result, returns false if the result is true. is Logical not Reverse 结果,如果结果为真则返回假。 Your second snippet does not work because, you write OR, OR returns true if one of the conditions is true.您的第二个代码段不起作用,因为您编写 OR,如果条件之一为真,则 OR 返回 true。

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

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