java java程序输出偶数/奇数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26363078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java program outputting even/odd numbers
提问by user3462263
My task is to write a java program that first asks the user how many numbers will be inputted, then outputs how many odd and even numbers that were entered. It is restricted to ints 0-100. My question is: What am I missing in my code?
我的任务是编写一个java程序,首先询问用户将输入多少个数字,然后输出输入了多少个奇数和偶数。它仅限于整数 0-100。我的问题是:我的代码中缺少什么?
import java.util.Scanner;
public class Clancy_Lab_06_03 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n;
System.out.println("How many numbers will be entered?");
n = input.nextInt();
while (n < 0 || n > 100) {
System.out.println("ERROR! Valid range 0-100. RE-Enter:");
n = input.nextInt();
n++;
}
int odd = 0;
int even = 0;
while (n >= 0 || n <= 100) {
n = input.nextInt();
if (n % 2 == 0) {
even++;
} else {
odd++;
}
}
System.out.println(even + "even" + odd + "odd");
}
}
回答by Kamil K?ys
Second while loop is infinite. Relplace it with something like this:
第二个while循环是无限的。用这样的东西代替它:
for (int i = 0; i < n; i++) {
int b = input.nextInt();
if (b % 2 == 0) {
even++;
} else {
odd++;
}
}
Also I don't understand why are you incrementing n
in first loop. For example when you will first give -5
, you will be asked to re-enter the number. Then you type -1
, but it gets incremented and in fact program processes 0
, altough user typed -1
. In my opinion it is not how it suppose to work and you should just remove this n++
.
我也不明白你为什么n
在第一个循环中递增。例如,当您第一次提供时-5
,系统会要求您重新输入号码。然后你输入-1
,但它会增加,实际上程序进程0
,尽管用户输入-1
。在我看来,这不是它应该如何工作,您应该删除它n++
。
As you asked in comment - the same using while
loop:
正如您在评论中所问的那样 - 使用while
循环相同:
while(n > 0) {
n--;
int b = input.nextInt();
if (b % 2 == 0) {
even++;
} else {
odd++;
}
}
Also it is good idea to close input
when you no longer need it (for example at the end of main method)
input
当您不再需要它时关闭它也是个好主意(例如在 main 方法结束时)
input.close();
回答by Jon Story
You had two issues - first you were incrementing n in the first loop, rather than waiting for the user to enter a valid number.
您有两个问题 - 首先,您在第一个循环中增加 n,而不是等待用户输入有效数字。
In the second loop, you weren't comparing the number of entries the user WANTED to make with the number they HAD made - you were over-writing the former with the new number.
在第二个循环中,您没有将用户想要创建的条目数量与他们已经创建的数量进行比较 - 您正在用新数字覆盖前者。
This version should work, although I've not tested it as I don't have java on this machine.
这个版本应该可以工作,虽然我没有测试过它,因为我在这台机器上没有 java。
Note that we now sit and wait for both inputs, and use different variable names for the "how many numbers will you enter" (n) and "what is the next number you wish to enter" (num) variables? Along with a new variable i to keep track of how many numbers the user has entered.
请注意,我们现在坐等两个输入,并为“您将输入多少个数字”(n)和“您希望输入的下一个数字是什么”(num)变量使用不同的变量名称?连同一个新变量 i 来跟踪用户输入了多少个数字。
import java.util.Scanner;
public class Clancy_Lab_06_03
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
int n;
System.out.println ("How many numbers will be entered?");
n = input.nextInt();
//Wait for a valid input
while (n < 0 || n > 100)
{
System.out.println ("ERROR! Valid range 0-100. RE-Enter:");
n = input.nextInt();
}
//Setup variables for the loop
int odd = 0;
int even = 0;
int num;
//Keep counting up until we hit n (where n is the number of entries the user just said they want to make)
for(int i = 0; i < n; i++)
{
//Changed this, because you were over-writing n (remember, n is the number of entries the user wants to make)
//Get a new input
while (num < 0 || num > 100)
{
System.out.println ("ERROR! Valid range 0-100. RE-Enter:");
num = input.nextInt();
}
//Check whether the user's input is even or odd
if (num % 2 == 0)
{
even++;
}
else
{
odd++;
}
}
System.out.println(even + " even. " + odd + " odd.");
}
}
回答by hfontanez
My suggestion to you is to have a clear separation of your requirements. From your post, you indicate you need to prompt the user for two distinct data items:
我对您的建议是明确区分您的需求。从您的帖子中,您表明您需要提示用户输入两个不同的数据项:
- How many numbers will be entered (count)
- The valuesto be analyzed
- 将输入多少个数字(计数)
- 要分析的值
It is a good practice, especially when you are learning, to use meaningful names for your variables. You are using 'n' for a variable name, then reusing it for different purposes during execution. For you, it is obvious it was difficult to figure out what was 'n' at a particular part of the program.
为变量使用有意义的名称是一种很好的做法,尤其是在学习时。您使用 'n' 作为变量名,然后在执行期间将其重用于不同的目的。对您来说,很明显很难弄清楚程序特定部分的“n”是什么。
Scanner input = new Scanner (System.in);
int count;
System.out.println ("How many numbers will be entered?");
count = input.nextInt();
//Wait for a valid input
while (count < 1 || count > 100)
{
System.out.println ("ERROR! Valid range 1-100. RE-Enter:");
count = input.nextInt();
}
Additionally, IMHO, a count of zero should not be valid. It does not make sense to run a program to evaluate zero values (don't bother a program that does nothing). I believe the lowest count should be one instead.
此外,恕我直言,零计数不应该是有效的。运行一个程序来计算零值是没有意义的(不要打扰一个什么都不做的程序)。我相信最低计数应该是一个。
int odd = 0;
int even = 0;
int value;
do
{
System.out.print("Enter a number between 0 and 100: ");
value = input.nextInt();
while (value < 0 || value > 100)
{
System.out.println ("ERROR! Valid range 0-100. RE-Enter:");
value = input.nextInt();
}
if (value % 2 == 0)
{
even++;
}
else
{
odd++;
}
count--; // decrement count to escape loop
} while (count > 0);
System.out.println(even + " even. " + odd + " odd.");
This example uses a do/while loop because in this case, it is OK to enter the loop at least once. This is because you do not allow the user to enter an invalid number of iterations in the first part of the program. I use that count variable directly for loop control (by decrementing its value down to 0), rather than creating another variable for loop control (for instance , 'i').
此示例使用 do/while 循环,因为在这种情况下,可以至少进入循环一次。这是因为您不允许用户在程序的第一部分输入无效的迭代次数。我将该计数变量直接用于循环控制(通过将其值减至 0),而不是为循环控制创建另一个变量(例如,'i')。
Another thing, slightly off topic, is that your requirements were not clear. You only indicated that the value was bounded to (inclusive) values between 0 and 100. However, how many times you needed to repeat the evaluation was not really clear. Most people assume 100 was also the upper bound for your counter variable. Because the requirement is not clear, checking a value greater or equal to 1 for the count might be valid, although highly improbable (you don't really want to repeat a million times).
另一件事,稍微偏离主题,是您的要求不明确。您只表示该值被限制为(包括)0 到 100 之间的值。但是,您需要重复评估多少次并不清楚。大多数人认为 100 也是您的计数器变量的上限。因为需求不明确,所以检查一个大于或等于 1 的值可能是有效的,尽管极不可能(你真的不想重复一百万次)。
Lastly, you have to pay attention to AND and OR logic in your code. As it was indicated, your second while loop:
最后,您必须注意代码中的 AND 和 OR 逻辑。正如所指出的,你的第二个 while 循环:
while (n >= 0 || n <= 100) {}
Is infinite. Because an OR evaluation only needs one part to evaluate to TRUE, any number entered will allow the loop to continue. Obviously, the intent was not allow values greater than 100. However, entering 150 allows the loop to continue because 150 >= 0. Likewise, -90 also allows the loop to continue because -90 <= 100. This is when pseudocode helps when you are learning. You wanted to express "a VALUE between lower_limit AND upper_limit." If you reverse the logic to evaluate values outside the limit, then you can say " value below lower_limit OR above upper_limit." These pseudocode expressions are very helpful determining which logical operator you need.
是无限的。因为 OR 评估只需要一部分来评估为 TRUE,所以输入的任何数字都将允许循环继续。显然,意图是不允许大于 100 的值。但是,输入 150 允许循环继续,因为 150 >= 0。同样,-90 也允许循环继续,因为 -90 <= 100。这是伪代码帮助你在学习。您想表达“lower_limit 和 upper_limit 之间的值”。如果您颠倒逻辑以评估超出限制的值,那么您可以说“值低于lower_limit 或高于upper_limit”。这些伪代码表达式非常有助于确定您需要哪个逻辑运算符。
I also took the liberty to add a message to prompt the user for a value. Your program expects the user to enter two numbers (count and value) but only one prompt message is provided; unless they enter an out of range value.
我还冒昧地添加了一条消息来提示用户输入一个值。您的程序希望用户输入两个数字(计数和值),但只提供一个提示信息;除非他们输入了超出范围的值。