0
我正在編寫一個程序,它需要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;
}
}
啊哈這個作品,謝謝。你碰巧知道這種方法是否使用平行陣列?我怎麼編輯異常來捕捉字母或符號(任何不是數字的東西,因爲程序只是簡單地指定數字......我認爲它是指整數或小數)。 @TurtleLoop – user3053348
只有一個數組(nums []),則此方法不使用並行數組。這裏有一個並行數組的例子:http://mathbits.com/MathBits/Java/arrays/ParallelArrays.htm – 2014-01-10 02:33:18