【发布时间】:2021-06-15 11:50:32
【问题描述】:
我需要从用户那里获取数组的长度和值,并返回显示次数最多的数字。例如:用户给了我长度“4”和数字 {83,238,8,54} 函数将返回“显示次数最多的数字是 8”; 但如果用户输入的数字通常超过 10 位,它会发送错误消息。
String sum = "";
// get the length
System.out.println("Enter the size of the array :");
int size = in.nextInt();
// create the array
String[] arr = new String[size+1];
// get value
System.out.println("Enter the elements of the array:(max capity 10 digits) ");
for(int i=0; i<arr.length; i++) {
arr[i] = in.nextLine();
sum+=arr[i];
}
System.out.println("the numbers that you gave me are: "+sum);
int all = Integer.parseInt(sum);
System.out.println("the digit that shows the most time is: "+maxOccurring(all));
}
static int countOccurrences(int x,int d) {
int count = 0;
while (x > 0)
{
if (x % 10 == d)
count++;
x = x / 10;
}
return count;
}
static int maxOccurring( int x)
{
if (x < 0)
x = -x;
int result = 0;
int max_count = 1;
for (int d = 0; d <= 10; d++)
{
int count = countOccurrences(x, d);
if (count >= max_count)
{
max_count = count;
result = d;
}
}
return result;
}
}
```
【问题讨论】:
-
非常感谢...我完全忘记了这部分...
标签: java java.util.scanner digits