【发布时间】:2013-10-21 20:03:00
【问题描述】:
我遇到了以下问题:
编写一个 Java 程序,提示用户输入 10 个正整数,然后找出最大值及其出现次数。提示:使用 While 循环。
示例运行:请输入 10 个数字:
1
2
46
1
0
5
46
46
6
27
最大值为:46,出现3次。
以下是我的解决方案:
import java.util.*;
public class numbers{
public static void main(String args[]){;
Scanner input=new Scanner (System.in);
int n=0;
int H=1;
int y=0;
System.out.println("please Enter 10 numbers:");
while (n<10){
int f=input.nextInt();
if ( f>n)
y=f;
else if(y==f)
H++;}
System.out.println("the biggest value is: "+
n+" and it is occurs "+
H+" times");
}}
但是结果不正确的问题:"(
我该怎么办?!
谢谢,但它会产生无限循环!
import java.util.*;
public class numbers{
public static void main(String args[]){;
Scanner input=new Scanner (System.in);
int n=0;
int H=0;
int y=0;
System.out.println("please Enter 10 numbers:");
while (n<10){
int f=input.nextInt();
if ( f>y){
y=f;
H=1;}
else if(y==f){
H++;
n++; }
}
System.out.println("the biggest value is: "+y+" and it is occurs "+H+" times");
}}
我终于发现了我的错误“感谢帮助”
更正我的代码后
import java.util.*;
public class numbers{
//main method
public static void main(String args[]){;
Scanner input=new Scanner (System.in);
int n=0;
int H=0;
int y=0;
System.out.println("please Enter 10 numbers:");
while (n<10){
int f=input.nextInt();//f the numbers
if(y==f)
H++;//to count how many repeat
if ( f>y){
y=f;// if numbers greater than y put value of f in y
H=1;}
n++;//to update counter
}
System.out.println("the biggest value is: "+y+" and it is occurs "+H+" times");
}// end main
}// end class
【问题讨论】:
-
怎么不正确?什么不工作?那标题是什么?
-
我觉得你的标题出了点问题
-
你的 while 循环有缺陷。切换数字时您不会重置
H++计数器,因此您只是在计算所有重复的数字。例如1 2 2 4 4 9将输出 4,因为有 4 个单独的数字有重复。 -
您应该学习如何使用调试器,并逐步检查您的代码,直到找到错误为止。
-
momcen ahad yhal?这是什么鬼?
标签: java