以下是我必须做的事情:
“写一段从键盘读取整数序列的代码,直到用户输入一个负数。然后输出偶数整数和读取的奇数整数(不包括最终数)记住 - 0是偶数。例如,如果序列是:
2 7 15 5 88 1243 104 -1那么输出应该是Number of even integers: 3 Number of odd integers: 4
我的代码在输入-1后仍然继续运行。我有一种感觉,我错过了{
某处或写错了代码。这是我的代码:
int oddCount = 0, evenCount = 0;
Scanner in = new Scanner(System.in);
while (oddCount>=0&&evenCount>=0){
System.out.print("Enter an integer: ");
int temp = in.nextInt();
if (temp>0) {
if (temp%2==0)
evenCount = evenCount + 1;
else oddCount = oddCount + 1;
while (temp>0);
System.out.println("Number of even integers: "+evenCount);
System.out.println("Number of odd integers: " +oddCount);
}
}
答案 0 :(得分:0)
这里有一些问题。
首先,由于您永不减少oddCount
和evenCount
,因此条件oddCount>=0&&evenCount>=0
始终为true
。
其次,你有一个无限循环的空循环,因为它的条件是true
并且它没有正文:while (temp>0);
我只是取出第一个循环,这是多余的,并使用do while
循环:
int oddCount = 0;
int evenCount = 0;
Scanner in = new Scanner(System.in);
do {
System.out.print("Enter an integer: ");
int temp = in.nextInt();
if (temp > 0) {
if (temp % 2==0) {
evenCount++;
} else {
oddCount++;
}
}
} while (temp > 0);
System.out.println("Number of even integers: " + evenCount);
System.out.println("Number of odd integers: " + oddCount);
答案 1 :(得分:0)
您的循环将始终继续,因为while (oddCount>=0&&evenCount>=0)
在您的情况下始终为真。试试这样:
int oddCount = 0, evenCount = 0;
Scanner in = new Scanner(System.in);
boolean continue = true;
while (continue){
System.out.print("Enter an integer: ");
int temp = in.nextInt();
if (temp>0) {
if (temp%2==0)
evenCount++;
else
oddCount++;
}
else {
System.out.println("Number of even integers: "+evenCount);
System.out.println("Number of odd integers: " +oddCount);
continue = false;
}
}
答案 2 :(得分:0)
我认为使用do while循环也会阻止你的观察,
int oddCount = 0;
int evenCount = 0;
Scanner in = new Scanner(System.in);
do {
System.out.print("Enter an integer: ");
int temp = in.nextInt();
if (temp > 0) {
(temp % 2==0)? evenCount++:oddCount++;
}
} while (temp > 0);
答案 3 :(得分:0)
您的代码只读取一个整数,然后停留在此行:while (temp>0);
以下代码解决了您的问题:
int oddCount = 0, evenCount = 0, temp;
Scanner in = new Scanner(System.in);
System.out.print("Enter an integer: ");
while (true) {
temp = in.nextInt();
if (temp < 0) {
break;
} else if (temp % 2 == 0) {
evenCount = evenCount + 1;
} else {
oddCount = oddCount + 1;
}
}
System.out.println("Number of even integers: " + evenCount);
System.out.println("Number of odd integers: " + oddCount);
答案 4 :(得分:0)
试试这个..
Scanner s=new Scanner(System.in);
int evenCount=0, oddCount=0;
while(true)
{
System.out.println("Enter a number");
int n=s.nextInt();
if(n<0) break;
if(n%2==0) evenCount+=n;
else oddCount+=n;
}
System.out.println("even count "+evenCount);
System.out.println("odd count "+oddCount);