我遇到了以下问题:
编写一个 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