2017-10-21 118 views
0

嗨即時創建一個Java程序的分數矩陣複用,我已經創建了一個類的分數,下面的代碼。矩陣乘法(分數)

public Fraccion (int n,int m){ 
    numerador = n; 
    denominador = m; 
} 

接收分子和分母,在我的主要功能我收到矩陣的大小,創建矩陣的2x2 3x3的等等...和即時通訊目前得到預期的輸出 。 我的問題是本身multiplicating矩陣,(因爲that's我想要什麼)

,所以這是我的主類代碼

private static void transicion() 
{ 
    //size of matriz 
    Fraccion[][] tmp = new Fraccion[cuantos][cuantos]; 
    //cloning the matrix to a temporal matrix 
    tmp = matrix.clone(); 
    //set boundaries for matrix so dont go out of bounds 
    int rowLimit = matrix.length; 
    int colLimit = matrix[0].length; 

    for (int i = 0; i < matrix.length; i++) 
    { 
     for (int j = 0; j < matrix[i].length; j++) 
     { 
      //method to multiply a fraction with another (producto_con) 
      if ((j+1<colLimit) && (matrix[i][j] == matrix[i][j+1])) 
       matrix[i][j].producto_con(tmp[i][j+1]); 
      if ((i+1<rowLimit) && (matrix[i][j] == matrix[i+1][j])) 
       matrix[i][j].producto_con(tmp[i][j+1]); 
      System.out.println(); 
      matrix[i][j].imprimete(); 
     } 
     System.out.println(); 
    } 

} 
//this is the method to multiply fractions on the fraction class 
public Fraccion producto_con(Fraccion laOtra){ 
    int numTmp, denTmp; 
    numTmp = numerator * laOtra.getnumerator(); 
    denTmp = denominator * laOtra.getdenominator(); 
    Fraccion laNueva = new Fraccion(numTmp,denTmp); 
    return laNueva; 
} 

但是當我打印方法transicion,打印相同的矩陣沒有變化,請提供任何幫助或建議?

+1

但你永遠不會使用'return laNueva;'值? –

回答

0

您正在創建新的Fraccion對象,但不會將它們分配給任何對象。所以......當然......沒有什麼變化。

一個更加陰險的問題是,你的分子和分母都被存儲爲int的值,並且你沒有什麼可以處理其中一個或另一個可能溢出的可能性。如果發生這種情況,你最終會得到垃圾值。

正確處理大於Integer.MAX_VALUE的分母/分子值是很困難的。

  • 最簡單的選擇是使用不會溢出的表示形式(用你的用例);例如BigInteger但這也是有限的...由你的堆大小。

  • 可以進一步推它,如果你能找到,並在分子和分母取消共同的因素,但分解是昂貴的...和頑固如果唯一因素是大素數。)

+0

好吧,所以現在即時通訊創建一個新的分數和分配方法的值,創建一個新的矩陣,在矩陣上輸入該值 –

+0

private static Fraccion nueva; Fraccion [] [] nuev =新Fraccion [cuantos] [cuantos]; nueva =矩陣[i] [j] .producto_con(tmp [i] [j + 1]); nuev [i] [j] = nueva; –

+0

這可能是正確的。測試它。 –