Correctly aligning columns in console output table and starting from zero

So I have this Java code where I am trying to output all 128 possible ASCII codes, their hexadecimal value and their decimal value. Here is the code I have.

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 ");
            }
    }
}

      

I am trying to achieve this :

Desired Output

However, my console output is not formatting correctly and my table is terribly misinterpreted as you can see [here] :

Current Output

Any help or ideas as to what I am doing wrong? In my code, I tried to fill in the gap left by zero due to some numbers being assigned to sounds or other characters that cannot be displayed correctly in the console and whatnot.

+3


source to share


1 answer


Instead of adding different types of symbols like:

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

      

you should try to set the correct number of characters that the value should be displayed on, you can do that with String.format, try changing the following syntax.

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

      



You can change your code to the following code which will do the job

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);
        }
    }

      

Also, there was a problem with the counter installed in the wrong place - you can try to change it to modulo.

+1


source







All Articles