Java不读“&&”陈述得当吗?

时间:2015-09-24 11:48:21

标签: java logical-operators

我的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);
    }
}

提前致谢!

3 个答案:

答案 0 :(得分:3)

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

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

要获得所需的结果,您可以使用num % 2 == 0num % 2 != 0替换模数测试。

答案 1 :(得分:1)

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

此处,-1%2不会导致1.因此,它不会增加negodd变量的值。

JAVA中,负数模数将与正数模数相同,但带负号。 0是中性的,因此它没有任何符号。

答案 2 :(得分:0)

-1%2将返回-1,而不是1,其中-2%2将返回0的结果。