【发布时间】:2015-09-24 11:48:21
【问题描述】:
我的 Java 代码有问题。具体来说,我的一个包含 && 的 if 语句没有像我期望的那样对某些输入返回 True。
有问题的sn-p:
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);
}
}
提前致谢!
【问题讨论】:
-
与其调用
System.exit(0),不如尝试使用return简单地从方法返回。 -
嗯,我还是编程新手,如果我在我的程序中加入新东西,我的教授不会将我的工作记录为正确的。在这个网站上仍然学到了很多东西。 :)
-
读取正确,但
num % 2永远不会是1的负数。