In: Computer Science
Write a program that prompts the user to enter a 3 x 3 matrix of double values and tests whether it is a positive Markov matrix. There will be two methods which will be called from the main method: public static double [] [] createArray() 1. Creates a 3 by 3 two dimensional array of doubles 2. Prompts the user for values as shown in the sample run 3. Stores the numbers in the array in the order entered 4. Returns the array to the main method public boolean isMarkovMatrix(double [][] matrix) 1. Returns false if any value in the array is negative 2. Prints the sum of each column in the array 3. Returns false if any the sum of any of the columns is not equal to 1.0 4. Otherwise, it returns true.
import java.util.Scanner;
public class Exercise_08_25 {
public static void main(String[] args) {
double[][] matrix=createArray();
System.out.println("It is" +(isMarkovMatrix(matrix)? " ":"not")+"a Markov matrix");
public static double[][] createArray(){
Scanner input=new Scanner(System.in);
double[][] m=new double[3][3];
System.out.println("Enter a 3-by-3 matrix row by row:");
for(i=0;i<m.length.i++){
for(int j=0;j<m[i].length;j++){
m[i][j]=input.nextDouble();
}
}
return m;
}
public static boolean isMarkovMatrix(double [][] m){
return isElementsPositive(m) && isEachColumnSum1(m);
}
public static boolean isElementsPositive(double [][] m){
for(int i=0;i<m.length;i++){
for(int j=0;j<m[j].length;j++){
if(m[i][j]<0)
return false
}
}
return true;
}
public static boolean isEachColumnSum1(double[][] m){
for(int col=0 ; col<m.length;col++){
double sum=0;
for(int row=0;row<m.length;row++){
sum=sum+m[row][col];
}
if (sum!=1)
return false;
}
return true;
}
}