2017-09-23 41 views
0

我可以用用戶輸入的數字打印2個二維數組,我也可以打印奇數,但我無法結合這兩種形式的代碼,因此奇數與其單元保持一致,不只是在一條印刷線上。我將如何打印奇數,將不可能作爲2 3x3數組中的空格? 下面有用於打印數組的代碼:如何從用戶輸入中打印2維數組java中的奇數?

public static void display (int[][] FirstArray, int[][] SecondArray) 
     { 
     //Print first array 
     System.out.print("Array1: \n"); 
     for (int row = 0; row < FirstArray.length; row++) 
     { 
      for(int column = 0; column < FirstArray[row].length; column++) 
      { 
       System.out.print(FirstArray[row][column] + " "); 
      } 
      System.out.println(); 
     } 
     //Print second array 
     System.out.print("Array2: \n"); 

     for (int row = 0; row < SecondArray.length; row++) 
     { 
      for(int column = 0; column < SecondArray[row].length; column++) 
      { 
       System.out.print(SecondArray[row][column] + " "); 
      } 
      System.out.println(); 
     } 
     } 
ex output: 
array 1:  array2 
3 3 3  4 4 4 
3 3 3  4 4 4 
3 3 3  4 4 4 

這裏是用於打印奇數而不在像上面的代碼中的3×3格式的代碼:

public static void display(int[][] FirstArray, int[][] SecondArray) 
{ 
    int count=0; 
    for (int i = 0; i < FirstArray.length; i++) { 
     for (int j = 0; j < FirstArray.length; j++) 
     { 
      if(FirstArray[i][j]%2==1) 
      { 
       System.out.println(m1[i][j]); 
      } 
     } 
     } 


    for (int i = 0; i < SecondArray.length; i++) { 
     for (int j = 0; j < SecondArray.length; j++) 
     { 
      if(SecondArray[i][j]%2==1) 
      { 
       System.out.println(SecondArray[i][j]); 
      } 
     } 
     } 

前輸出: 3 3 3 3 3 3 3 3 3(奇數顯示,但在一行中)

Ex output of what Im looking for(assuming i entered in even numbers too): 
3 3 3 
    3  3 3 
3   3 

回答

0

您可以糾正你的打印語句在兩個迴路爲:

for (int i = 0; i < FirstArray.length; i++) { 
    for (int j = 0; j < FirstArray.length; j++) { 
    if(FirstArray[i][j]%2==1) { 
     System.out.print(m1[i][j] + " "); // odd number and space 
    } else { 
     System.out.print(" "); // blank space for even numbers 
    } 
    } 
    System.out.println(); // next line for next row 
}