有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

循环x%2>0在java中意味着什么?

我目前正在我的在线课程中学习java,我正在学习循环(特别是continue和break语句)。给我的例子是:

int j = 0
while (true){
    System.out.println();
    j++;
    System.out.print(j);
    if (j%2 > 0) continue
    System.out.print(" is divisible by 2");
    if (j >= 10) break;
}

我不明白为什么它是(j%2>;0)而不是(j%2==0),因为如果“j”是5,那么你做5%2会怎么样。你得到的号码不是1吗?还是我遗漏了什么?有人能给我解释一下吗? (对不起,我不是。我的问题有点让人困惑。我以前从未使用过这个网站,而且我还很年轻)


共 (4) 个答案

  1. # 1 楼答案

    让我向你解释。请参见每行旁边的注释

    int j = 0          
    while (true){
        System.out.println();
        j++;                   //increases the value of j on the next line by 1.
        System.out.print(j);   //prints 1, the first time because of above, 0 + 1.
        if (j%2 > 0) continue  //using modulus operator(%) we are doing 1 % 2, answer is 1
                               //since 1 % 2(if 1 is divisible by 2) > 0 we are 
                               //continue statement breaks the iteration in the 
                               //loop, so anything below this line won't be 
                               //executed.
        System.out.print(" is divisible by 2");//this line will only be executed
                                               //if j is divisible by 2. that is 
                                               //j is divisible by 2 (j%2 == 0)
        if (j >= 10) break;                    //when j is equal or greater than 
                                               //0 we are stopping the while loop.
    }
    
  2. # 2 楼答案

    继续意味着“转到循环的顶部,跳过循环的其余代码”,而不是“继续代码”。既然5%2是1,那么1>;0时,将执行continue,直接转到循环的顶部并跳过正文的其余部分

    他们为什么使用>;0而不是!=0? 没有任何技术原因,只是风格不同。我个人会用后者,因为它在我的脑海中更清晰。但两者都有效

  3. # 3 楼答案

    int j = 0;
    while (true){
        System.out.println();
        j++;
        System.out.print(j);
    // in this case you won't print any message and you  
    // are sure that the next number is even (j will be incremented by "continue;").
        if (j%2 > 0) continue; 
        System.out.print(" is divisible by 2");
        if (j >= 10) break;
    }
    
  4. # 4 楼答案

    X%2表示X除以2时的余数。因此,如果x/2的余数大于0,则表示x是奇数。当x%2==0时,x是一个正数