我想寫一個java程序,打印用戶輸入3x3多維數組是否是馬爾可夫矩陣;提示如下。檢查用戶輸入3x3多維數組是否是一個馬爾可夫矩陣
- 如果每個 -element爲正,且每列中的元素總和爲1,則將n×n矩陣稱爲正馬爾可夫矩陣。編寫以下方法以檢查矩陣是否爲馬爾可夫矩陣。
public static boolean isMarkovMatrix(double [][] m)
-Write的測試程序(主法),提示用戶輸入雙 - 值和測試是否它是一個馬爾可夫矩陣的3×3 --matrix。
我的代碼輸出打印出來,不管我輸入什麼,它都不是一個馬爾科夫矩陣,也不知道爲什麼它會這樣做。作爲一個方面說明,我不知道任何複雜的java,並且只在課上幾周,所以下面是我的java編程技巧的程度。任何幫助,將不勝感激!先謝謝你。
import java.util.Scanner;
public class Problem3 {
public static void main(String[] args) {
//declarations
double[][] markov = new double[3][3];
Scanner keyboard = new Scanner(System.in);
//input
System.out.print("Please enter numbers to fill up a 3x3 matrix: ");
for (int i = 0; i < markov.length; i++) {
for (int x = 0; x < markov.length; x++) {
markov[i][x] = keyboard.nextDouble();
}
}
//output
if (isMarkov(markov) == true) {
System.out.print("Your matrix is a Markov Matrix!");
} else if (isMarkov(markov) == false) {
System.out.print("Your matrix is not a Markov Matrix!");
}
//close keyboard
keyboard.close();
}
//method to check whether the matrix is positive
public static boolean isPositive(double[][] array) {
//declarations
boolean answer = true;
//processing
for (int i = 0; i < array.length; i++) {
for (int x = 0; x < array.length; x++) {
if (array[i][x] < 0) {
answer = false;
}
}
}
return answer;
}
//method to check whether the sum of the columns are 1
public static boolean columnSum(double[][] array) {
//declarations
double sum = 0;
boolean answer = true;
//processing
for (int i = 0; i < array.length; i++) {
for (int x = 0; x < array.length; x++) {
sum += array[i][x];
}
if (sum != 1) {
answer = false;
}
}
return answer;
}
//method to check whether the matrix is a Markov matrix
public static boolean isMarkov(double[][] array) {
//declarations
boolean answer = false;
//processing
if ((isPositive(array) == true) && (columnSum(array) == true)) {
answer = true;
}
return answer;
}
}
在你的columSum方法中,pb是sum!= 1。由於浮點,你不會比較那樣的雙倍。使用Java.lang.Double.compare().https://www.tutorialspoint.com/java/lang/double_compare.htm – Incognito