跳过数组显示中的行

时间:2017-03-19 15:18:47

标签: java arrays

此程序显示n行和n列的数组;其中n由用户输入。显示应该是nn数组,但在此程序中只显示一行。

例如,如果用户输入3,则输出应为

1 2 3
4 5 6
7 8 9

相反,它显示

1 2 3 4 5 6 7 8 9

有人可以帮我吗?感谢

public class Question2 {

  public static void main(String[] args) {

//Title
    System.out.println("[----------------------]");
    System.out.println("[     Array Pattern    ]");
    System.out.println("[----------------------]");
    System.out.println("");

//declare scanner
    Scanner keyboard = new Scanner (System.in);

//Prompt user to enter a digit greater than or equal to 3
    System.out.println("How many rows/columns do you want your array to have? (Must be at least 3):");

//read user input
    int num = keyboard.nextInt();

//place constraints on int num so that if it is less than 3, the program does not execute
    while(num<3 )
    {
        System.out.println("Lets's try this again....");
        System.out.println("How many rows/colums do you want your array to have? (Must be at least 3):");
        num = keyboard.nextInt();   
    }

    //2D array with number of rows and columns entered by user
    int[][] array = new int [num][num];
    int inc=1;
    for(int i=0;i<array.length;i++)
        for(int j=0;j<array.length;j++)
    {
    array[i][j]=inc;
    inc++;

    }


    //replace all square brackets in array display 
    String a = Arrays.deepToString(array);
    a = a.replace("[", "").replaceAll("]","");

    //replace all commas in array display
    a = a.replace(",", "").replaceAll(",","");
    System.out.println(a);

  }

}

2 个答案:

答案 0 :(得分:0)

不要将数组转换为字符串;这只是必要的工作。相反,循环遍历元素,打印每个元素,然后在每个第三个元素后添加换行符,如下所示:

for (int i = 0; i < array.length; ++i) {
    print(i);   // print the number *without* a line break after it

    if (i % 3 == 0) {
        println();    // add a line break after every third element
    } else {
        print(" ");
    }
}

println();

答案 1 :(得分:0)

您不需要Arrays.deepToString

相反,请使用嵌套的for循环,与执行inc++的代码完全相同。

主要想法是这样的:

foreach row in array:
    print all values
    print a linebreak, via `System.out.println()`

要打印行中的所有值,请使用另一个for循环。在该循环中,您可以使用System.out.printf("%5d", value)打印一个数字并用足够的空格将其包围,以便输出看起来格式正确。

有关更多提示,请参阅Java中乘法表的Rosetta Code示例。

相关问题