为什么 CodeB 不打印 42 而 CodeA 打印 42?

Why doesn't CodeB prints 42 while CodeA does print 42?

我是初学者。我解决了 Spoj 上的第一个经典问题。 但是我写的第一个代码无法解决这个问题,因为 42 包含在输出中。第二个代码解决了这个问题,因为它不打印 42。但我仍然无法弄清楚它是如何工作的。为什么代码 A 打印 42 而代码 B 不打印?请帮帮我!

代码A

public class CodeA {
    public static void main(String[]args) {
        Scanner input = new Scanner(System.in);
        int n = 0;
        while(true) {
            if(n!=42) {
               n = input.nextInt();               
               System.out.println(n);
            }
            else{
                break;
            }
       }
   }
}

代码B

public class CodeB {  
    public static void main(String[]args) {

       Scanner in = new Scanner(System.in);

       while(true) {
          int n = in.nextInt();
          if(n == 42) {
            break;
          }
          System.out.println(n);
       }
    }
}

代码A:

    while(true) {
        if(n!=42) {
            n = input.nextInt();   // Number is read here
            System.out.println(n); // and unconditionally (always) printed here, 42 or not
        }
        else{
            break; // At next iteration, if last number read was 42
                   // you break out of the "while" loop
        }
    }

代码B:

   while(true) {
      int n = in.nextInt();
      if(n == 42) {
        break;    // You break here...
      }
      System.out.println(n); // ... so this is skipped...
   }
   // ... because execution resumes here.

您对 code b 有什么期望?

你写了 if(n == 42) 并放了一个 break 吗?这是什么意思 ?不是说你想逃吗?

那它有什么作用呢?当你输入 42

时它会逃逸

break 适用于 while,不适用于 if 代码 b 中,当 n==42 您的输出 System.out.println(n) 无法访问时。

如果你需要n在等于42时打印,那么你可以使用

if(n == 42) {
   System.out.println(n);
   break;
}