我可以使用用户输入的数字打印2个2D数组,我也可以打印奇数,但是我在组合两种形式的代码时遇到了麻烦,因此奇数与单元格保持一致而不只是在一条印刷线上。我如何打印奇数,将非赔率作为2个3x3阵列中的空白? 下面是打印数组的代码:
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
以下是不使用3x3格式打印奇数的代码,如上面的代码:
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 :(得分:0)
您可以将两个循环中的print语句解决为:
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
}
答案 1 :(得分:0)
Scanner sc = new Scanner(System.in);
System.out.println("Enter numbers of rows : ");
int n = sc.nextInt();
System.out.println("Enter number of colmns : ");
int m = sc.nextInt();
int[][] array = new int[n][m];
System.out.println("Enter elements of array : ");
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.print(" X[ " + i + "," + j + "] = ");
array[i][j] = sc.nextInt();
}
}
System.out.print("Even numbers on position :");
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
if (array[i][j] % 2 != 0) {
System.out.print(array[i][j] + " ");
}
}
}