用Java格式化表

时间:2014-02-28 03:53:30

标签: java format tabular

这是此作业的主要步骤。创建嵌套循环以打印出来 如果输入有效,则以表格格式表示数字。第一个输入i定义了数字
行,第二个输入j定义列数。在循环内部, 编写代码以列出从1到i * j的正数。使用 具有“%4d”和“%4s”格式的System.out.printf()函数 整数和字符串。

我需要打印

设置表和数据类型的大小(键入'Q'或'q'退出): 3 4“数字”

  • | 1 2 3 4

------------- ------

1 | 1 2 3 4

2 | 5 6 7 8

3 | 9 10 11 12

在我设置了列数和行数后,我只能得到内部表,而不是外部数字表或星号。 为了让它正确显示我必须改变它,但它应该排列整齐

    Scanner scan = new Scanner(System.in);
    String stringIn;

    do
    {
        System.out.print("Set the size of table and data-type(Type Q or q to quit)");
        stringIn = scan.nextLine();
        int space = stringIn.indexOf(" ");
        int spaceTwo = stringIn.indexOf(" ", space+1);

        if(stringIn.length()>4)
        {

            String firstNum = stringIn.substring(0,space);
            String secondNum = stringIn.substring(space+1,spaceTwo);
            String dataType = stringIn.substring(spaceTwo+1);
            int firstInt = Integer.parseInt(firstNum);
            int secondInt = Integer.parseInt(secondNum);

            if (!stringIn.equals("Q")&&!stringIn.equals("q")&&firstInt>=0&&secondInt>=0)
            {
                System.out.println(stringIn.substring(0,space) + " " + stringIn.substring(space+1,spaceTwo) + " " + stringIn.substring(spaceTwo+1));
            }
            else if(firstInt<0||secondInt<0)
            {
                System.out.println("Try again. The input was invalid");
            }
            for(int i = 1; i <firstInt+1; i++)
            {
                for (int j = 1; j < secondInt+1; j++)
                {
                    System.out.printf("%4d", i*j);
                    System.out.printf("%4s", i*j);
                }
                System.out.println();
            }
        }

    }
    while(!stringIn.equals("Q")&&!stringIn.equals("q"));

这是我的第一个Java类,因此我的代码非常混乱。

1 个答案:

答案 0 :(得分:1)

你非常接近,只是稍微偏离嵌套循环中的逻辑。这就是我修改的内容:

1)将列标签移到内环

之外

2)创建了一个用于单元格值的计数器

3)使用计数器打印单元格值&amp;然后增加它

代码:

String headerRow= " * |"; 
String spacer = "-----";
for(int i=1; i<secondInt + 1; i++){headerRow+="   "+i; spacer+="----";}
System.out.println(headerRow);
System.out.println(spacer);
int counter = 1;
for (int i = 1; i < firstInt + 1; i++) {
    System.out.printf("%4s", i + " |");
    for (int j = 1; j < secondInt + 1; j++) {
        System.out.printf("%4d", counter);
        counter++;
    }
    System.out.println();
}

该代码输出:

> 4 5 numbers  
* |   1   2   3   4   5
> -------------------------  
1 |   1   2   3   4   5  
2 |   6   7   8   9  10  
3 |  11  12  13  14  15  
4 |  16  17  18  19  20