2017-09-23 98 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 
}