2017-10-01 9 views
0

私が書いたプログラムは、3行3列の行列を乗算します。これは、ユーザに行列aと行列bを入力するように要求し、次にその行列を出力します。私はこれをしましたが、私の唯一の問題は、出力がmatrix a * matrix b = product(a,b)を印刷したい製品だけを印刷することです。私は の上にSystem.out.println(a[i][j]+ " ");を置こうとしましたが、すべての出力と乗算を駄目です。行列を印刷します。

//this is my code: 
import java.util.Scanner; 

public class Matrices 

{ 

public static double[][] multiplyMatrix(double[][] a,double[][] b) 

{ 

     double c[][]=new double[3][3]; 

     for(int i=0;i<3;i++) 

      for(int j=0;j<3;j++) 

       for(int k=0;k<3;k++) 

        c[i][j]=c[i][j]+a[i][k]*b[k][j]; 

     return c; 

    } 


    public static void main(String args[]) 

{ 

     //Create Scanner object to read input from user 

     Scanner sc=new Scanner(System.in); 

     double a[][]=new double[3][3]; 

     double b[][]=new double[3][3]; 

     double sum[][]=new double[3][3]; 

     double mul[][]=new double[3][3]; 



     //Read the elements of matrix b 

     System.out.println("Enter the elements of matrix a:"); 

     for(int i=0;i<3;i++) 

      for(int j=0;j<3;j++) 

       a[i][j]=sc.nextInt(); 


    System.out.print(a[i][j]+"") 
     //Read the elements of Matrix b 

     System.out.println("Enter the elements of matrix b:"); 

     for(int i=0;i<3;i++) 

      for(int j=0;j<3;j++) 

       b[i][j]=sc.nextInt(); 


     //Call the method multiplyMatrix to multiply a and b 

     mul=multiplyMatrix(a,b); 


     System.out.println("Multiplication of two matrices:"); 




     for(int i=0;i<3;i++) 

     { 

      for(int j=0;j<3;j++) 


      { 

      System.out.print(mul[i][j]+"");     

      } 

      System.out.println(); 

      } 

     } 

    } 

答えて

0

列賢い出力:あなたは出力3つの行列するために、三つの異なるループを使用する必要があります:(a、b)は

for(int i=0;i<3;i++){ 
    for(int j=0;j<3;j++) 
    { 
     System.out.print(a[i][j]+" ");     
    } 
    System.out.println(); 
} 

for(int i=0;i<3;i++){ 
    for(int j=0;j<3;j++) 
    { 
     System.out.print(b[i][j]+" ");     
    } 
    System.out.println(); 
} 

for(int i=0;i<3;i++){ 
    for(int j=0;j<3;j++) 
    { 
     System.out.print(mul[i][j]+" ");     
    } 
    System.out.println(); 
} 

行賢明出力*行列B =製品をマトリックス:作成各行のStringBuffer行列a、b、mulの1行目をStringBuffer1に追加して、それを印刷します。他の2つの行についても同様です。 ここに、StringBufferの構文のリンクがあります。 http://www.java-examples.com/java-stringbuffer-examples

+0

それは私はそれが行 – Andrey

+0

に印刷するのですかどの列でそれを印刷し、あなたが投稿したときに、より具体的にしてください質問。 – Vidhi

0

あなたはこれを使用して試すことができます:

System.out.println("Multiplication of two matrices:" + "\n"); 

System.out.println("Matriz A"); 

System.out.println(Arrays.deepToString(a) + "\n"); 

System.out.println("Matriz B"); 

System.out.println(Arrays.deepToString(b)+ "\n"); 

System.out.println("A x B"); 

System.out.println(Arrays.deepToString(mul)+ "\n"); 

結果:

Multiplication of two matrices: 

Matriz A 
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]] 

Matriz B 
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]] 

A x B 
[[30.0, 36.0, 42.0], [66.0, 81.0, 96.0], [102.0, 126.0, 150.0]]