Java 没有正确阅读“&&”语句?

Java not reading "&&" statements properly?

我的 Java 代码有问题。具体来说,我的一个包含 && 的 if 语句没有像我期望的那样为某些输入返回 True。

相关代码段:

if (num%2==1 && num < 0) {       //why is not reading this statement?
    negodd ++;
}

示例输入和输出与预期输出:

 Enter any number to continue. Enter 0 to stop :
 1
 2
-2
-1
 0   // not counted as a number since it is a stop function.

Output of my code.                     What it should be.
You Entered 4 numbers :               You Entered 4 numbers :
1 negative even                         1 negative even
1 positive even                         1 positive even                         
0 negative odd                          1 negative odd  <--should read the 1
1 positive odd                          1 positive odd

完整代码以防万一:

 import java.util.Scanner;
 public class stupid {
     public static void main(String[] args) {
         Scanner x = new Scanner(System.in);
         int num = 0;
         int negodd = 0, count = 0, posseven = 0;
         int possodd = 0; int negeven=0;

         System.out.println("Enter any number to continue. Enter 0 to stop : ");
         num = x.nextInt();

         if(num==0){
             System.out.print("You immediately stop");
             System.exit(0);
         }

         while (num != 0) {
             count ++;
             if (num%2==1 && num > 0) {
                 possodd ++;
             } 
             if (num%2==1 && num < 0) {       //why is not reading this statement?
                 negodd ++;
             }
             if (num%2==0 && num > 0) {
                 posseven ++;
             }
             if (num%2==0 && num < 0) {
                 negeven++;
             }
             num = x.nextInt();
         }
         System.out.printf("You Entered %d numbers\n",count);
         System.out.printf("%d negative even \n",negeven);
         System.out.printf("%d positive even\n",posseven);
         System.out.printf("%d negative odd\n",negodd);
         System.out.printf("%d positive odd\n",possodd);
    }
}

提前致谢!

-1 % 2 将变为 return -1,而不是 1,其中 -2 % 2 将给出结果 0.

对负数使用取模运算符会得到与您想象的不同的结果。

1 % 2 == 1
2 % 2 == 0
-2 % 2 == 0
-1 % 2 == -1

要获得您想要的结果,您可以将模测试替换为 num % 2 == 0num % 2 != 0

1 % 2 == 1
2 % 2 == 0
-2 % 2 == 0
-1 % 2 == -1

在这里,-1%2 不会产生 1。因此,它不会增加 negodd 变量的值。

JAVA中,负数取模的结果与正数取模的结果相同,但带有负号。 0 是中性的,因此它不会有任何符号。