[英]Max and Number of occurrences
In my lab, we have to have the user input numbers, until they enter '0'. 在我的实验室中,我们必须让用户输入数字,直到他们输入“ 0”。 The program will then find the max, count the number of occurrences, and output both numbers.
然后,程序将找到最大值,对出现的次数进行计数,并输出两个数字。
Here's my code: 这是我的代码:
Scanner scan = new Scanner(System.in);
int max = Integer.MIN_VALUE, count = 0, num;
System.out.println ("Enter a number (Enter a 0 to stop): ");
num = scan.nextInt();
while (num != 0){
System.out.println ("Enter a number: ");
num = scan.nextInt();
if (num >= max){
max = num;
count ++;
}
}
System.out.println("\nMax number was: " + max);
System.out.println("Number of occurrences: " + count);
Now when it outputs, sometimes I get the right answer and sometimes not. 现在输出时,有时我得到正确的答案,有时却没有。 I figure I just have the loop wrong or maybe the counter needs to be reset, but I can't figure it out.
我认为我只是循环错误,或者可能需要重置计数器,但我无法弄清楚。
For example: 例如:
If I enter: 3, 5, 2, 5, 5, 5, 0 如果我输入:3、5、2、5、5、5、0
The output reads: Max number was: 5 Number of occurrences: 4 输出为:最大数量为:5出现次数:4
But if I enter: 3, 5, 9, 2, 5, 9, 0 但是如果我输入:3、5、9、2、5、9、0
The output reads: Max number was: 9 Number of occurrences: 3 输出为:最大数量为:9出现次数:3
Just looking for some advice. 只是在寻找一些建议。
If num > max
, then it's the first occurrence of the max, and count
should be set to 1. If num == max
, then it's another occurrence of the max, and count
should be incremented. 如果
num > max
,则它是num > max
的第一个出现,并将count
设置为1。如果num == max
,则其是num == max
的另一个出现,并且count
应该增加。
Also, as @doelleri correctly mentions in a comment, the first number is ignored. 另外,正如@doelleri在评论中正确提及的那样,第一个数字将被忽略。
The best loop to use here is the do...while
在这里使用的最佳循环是
do...while
Here is a correction to your code : 这是您的代码的更正:
You'll have to reset the count
variable only if a new max
is found. 仅当找到新的
max
才需要重置count
变量。
do{
System.out.println ("Enter a number: ");
num = scan.nextInt();
if (num > max){
max = num;
count = 1;
} else if (num == max){
count++;
}
}while (num != 0);
System.out.println("\nMax number was: " + max);
System.out.println("Number of occurences: " + count);
找到新的最大值后,您需要重置计数变量。
You need to reset the counter when ever you observe a new max value. 每当观察到新的最大值时,都需要重置计数器 。 Also you should use
do-while
instead of a while
loop. 另外,您应该使用
do-while
不是while
循环。 Because do-while
loop always executes once, so you can take the user input in the loop. 由于
do-while
循环始终执行一次,因此您可以在循环中获取用户输入。
Scanner scan = new Scanner(System.in);
int max = Integer.MIN_VALUE, count = 0, num;
System.out.println ("Enter a number (Enter a 0 to stop): ");
do {
System.out.println ("Enter a number: ");
num = scan.nextInt();
if (num >= max){
count = num == max ? count+1 : 1;
max = num;
}
}while(num != 0);
System.out.println("\nMax number was: " + max);
System.out.println("Number of occurences: " + count);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.