繁体   English   中英

在同一行中打印一个变量号,到 go 到这些变量号之后的下一行

[英]Printing a variable numbers in the same line, to go to the nexline after these variable number

我想让用户输入列长度。 让我们说“4”。 然后它应该像这样打印输出:

1 2 3 4

5 6 7 8

9 10 11 12

13 14 15 16

在 4 x 4 的正方形中。

我不希望我的代码接近我正在寻找的解决方案。 这只是一个简单的打印输出行。 但这需要一些必要的修改。

我该如何管理?


package MagicMatrix;

import java.util.Arrays;
import java.util.Scanner;

public class Matrix
{

    Scanner scanner = new Scanner(System.in);   

    public static void main(String[] args)
    {

        new Matrix();

    }

    public Matrix() 

    {

        System.out.println("Give column length of matrix\n");

        int var00 = 1;
        int columnlength = scanner.nextInt();

        int [][] matrix = new int [columnlength][columnlength];


        for (int i=0; i < columnlength; i++) 
        {
            for (int j=0; j < columnlength; j++ )
            {
                matrix[i][j] = var00;
                var00++;
            }
        }

        for (int i=0; i < colomnlength; i++) 
        {
            for (int j=0; j < colomnlength; j++ )
            {

            System.out.print(matrix[i][j]); // The big question!!!!

            }
        }
    }

}

与您在问题中所说的相反,您实际上非常接近解决方案。 你只需要用你的var00替换var1 (我不知道它是从哪里来的),并在内部循环之后(用j迭代的那个)添加一个System.out.println()到 go 到下一行排。 这在理论上应该可行。

for (int i=0; i < columnlength; i++) 
    {
        for (int j=0; j < columnlength; j++ )
        {
            matrix[i][j] = var00;
            var00++;
        }
    }

for (int i=0; i < columnlength; i++)
    {
        for (int j=0; j < columnlength; j++ )
            {
                System.out.print(matrix[i][j] + " "); 
            }
        System.out.println();
    }

编辑:我注意到你把它叫做columnlengthcolomnlength你应该修复它。 还要在matrix[i][j]之后添加一个空格+ " "所以数字之间有一点空格

您也可以通过仅使用两个循环来实现这一点。

import java.util.Scanner;

public class Hello
{
    public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);   

    int columnlength = scanner.nextInt();

    int [][] matrix = new int [columnlength][columnlength];
    int counter = 1;

    for(int i = 0;i<columnlength;i++) {
        for(int j=0;j<columnlength;j++) {
            matrix[i][j] = counter;
            System.out.print(counter+++"\t");
        }
        System.out.println();
    }

}

}

不确定我是否完全理解您的问题,也许这会解决您的问题:

    for (int i=0; i < colomnlength; i++) 
    {
        System.out.print(matrix[i][0]);
        for (int j=1; j < colomnlength; j++ )
        {

            System.out.print(matrix[i][j]); // The big question!!!!

        }
        System.out.println();
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM