我正在编写一个程序,它接受10个数字作为输入,并使用并行数组显示数字的模式,以及将数字数组作为参数并返回数组中最常出现的值的方法。问题:然而,当我运行我的程序时它绝对没有输出,而且,我不知道如何实现并行数组。 有人知道吗? 谢谢。
import java.util.Scanner;
公共类模式{
public static void main(String[] args) {
}
public int computeMode(int[] nums) {
Scanner scanner = new Scanner(System.in);
int maxValue = -1;
int maxCount = 0;
int x = 0;
//count how many times nums[i] appears in array
System.out.println("Enter 10 numbers: ");
for (int i = 0; i < 10; i++) {
try { //try catch exception to catch decimal inputs as well as more /less than 10 integers
x = scanner.nextInt();
} catch (Exception e) {
System.out.println("Invalid input! Please reenter 10 integer values.");
scanner = new Scanner(System.in);
i = -1;
continue;
}
for (i = 0; i < nums.length; i++) {
int count = 0;
for (int j = 0; j < nums.length; j++) {
if (nums[j] == nums[i]) {
count++;
}
}
if (count > maxCount) {
maxValue = nums[i];
maxCount = count;
System.out.println("The mode is: " + maxValue);
}
}
}
return maxValue;
}
}
答案 0 :(得分:2)
主要功能是空的,所以它什么都没有, 并且该功能不需要任何参数,因为您使用扫描仪读取数字
我认为你需要这个:
import java.util.Scanner;
class Mode {
public static void main(String[] args) {
computeMode();
}
public static void computeMode(){
int nums[]=new int[10];
Scanner scanner = new Scanner(System.in);
int maxValue = -1;
int maxCount = 0;
int x = 0;
//count how many times nums[i] appears in array
System.out.println("Enter 10 numbers: ");
for (int i = 0; i < 10; i++) {
try { //try catch exception to catch decimal inputs as well as more /less than 10 integers
x = scanner.nextInt();
nums[i]=x;
}
catch (Exception e) {
System.out.println("Invalid input! Please reenter 10 integer values.");
i =i -1;
scanner.nextLine();
continue;
}
}
for (int i = 0; i < nums.length; i++) {
int count = 0;
for (int j = 0; j < nums.length; j++) {
if (nums[j] == nums[i]) {
count++;
}
}
if (count > maxCount) {
maxValue = nums[i];
maxCount = count;
}
}
System.out.println("The mode is: " + maxValue);
}
}
答案 1 :(得分:0)
代码写x
,但从不读它;读nums
,但从不写;并实现computeMode
,但从不调用它。