我得到了以下的问题:搜索和计数最大价值
写,提示用户输入10个正整数,然后找到其出现的最大的价值和数量的Java程序。提示:使用While循环。
Sample Run: please enter 10 numbers:
1
2
46
1
0
5
46
46
6
27
The biggest value is: 46 and It occurs 3 times.
下面是我的解决办法:
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个单独的数字有重复。 –