【问题标题】:Aligning columns in a console output table correctly and starting to count from zero正确对齐控制台输出表中的列并从零开始计数
【发布时间】:2013-01-16 22:54:08
【问题描述】:

所以我得到了这个 Java 代码,我试图在其中输出所有 128 个可能的 ASCII 代码、它们的十六进制值和十进制值。这是我现在的代码。

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {


            Scanner Number = new Scanner(System.in);
            System.out.println("How many groups: ");
            int usernumber = Number.nextInt();

            int counter = 0;

            for (int i = 0; i < 1; i++) {
                for (int j = 0; j < 128; j++) {
                   String output = "";
                    if (j == 7 | j == 8 | j == 9 | j == 10 | j == 13){
                      output += " ";
                    } else {
                       output += (char) j;
                    }
                    output += " " + j + " " + Integer.toHexString(j);

                    if (Integer.toHexString(j).length() < 2){
                        output += "     ";
                    } else {
                        output += "\t";
                    }

                    if (counter == usernumber) {
                        output += "\n";
                        counter = 0;
                    }

                    System.out.print(output);
                    counter++;
                }
                System.out.println("\n ");
            }
    }
}

我正在努力实现这个

但是,我的控制台输出格式不正确,并且我的表格被严重误解,如您所见 [此处]

关于我做错了什么有任何帮助或想法吗?在我的代码中,由于某些数字被分配给无法在控制台中正确输出的声音或其他字符等等,我试图弥补留空的空间。

【问题讨论】:

  • 使用制表符格式化可能会产生不需要的结果。据我所知,上面的例子很可能会与恒定间距一起使用。每个字符只占用一个空格,不需要考虑字符串长度。

标签: java netbeans console console-application


【解决方案1】:

而不是添加不同类型的字符,如:

if (Integer.toHexString(j).length() < 2){
    output += "     ";
} else {
    output += "\t";
}

您应该尝试设置显示值的正确字符数,您可以使用 String.format 进行设置,尝试更改以下语法。

String.format("%-2s - %-2d", stringValue, intValue);

您可以将您的 for 更改为以下代码,这将完成这项工作

for (int j = 0; j < 128; j++) {
        counter++;
        char firstChar = (char) j;
        if (j == 7 || j == 8 || j == 9 || j == 10 || j == 13) {
            firstChar = ' ';
        }
        String output = String.format("%-3s %-3d %-4s", firstChar, j, Integer.toHexString(j));

        if (counter == usernumber) {
            System.out.println(output);
            counter = 0;
        }else{
            System.out.print(output);
        }
    }

此外,计数器设置在错误位置存在问题 - 您可以尝试将其更改为模数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-05
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-31
    相关资源
    最近更新 更多