joe smith
joe smith

Reputation: 29

How would I print each of the characters 5 per line, with its number representation as well

public class UnicodeTable {

    public static void main(String[] args) {

        //declarations
        int count;
        final char Per_Line = 5;
        //instantaition
        count = 0;

        for (int i = 0; i <256; i++ ){
            System.out.println( (char)i );

            ++count;
        }
    }

}

so I created a for loop that prints all the characters. I want to print five number/character pairs per line, with each pair separated by tab characters and their number representation as well so (00065 A 00066 B 00067 C 00068 D 00069 E). So I have it printing all of them but I only want 5 per line. So would I do an if statement with mod equaling 0?

Upvotes: 2

Views: 1357

Answers (4)

ccc
ccc

Reputation: 370

This program lets you to get all chars and ints of them from 00035 # to 00256 Ā

public static void main(String[] args) {
    //declarations
    int count;
    final char Per_Line = 5;
    //instantaition
    count = 0;
    for (int i = 35; i < 257; i++) {
        if (countOf(i) == 2) {
            System.out.print("000" + i + "\t" + (char) i + "\t");
            if (i % 5 == 4) {
                System.out.println();
            }
        } else {
            System.out.print("00" + i + "\t" + (char) i + "\t");
            if (i % 5 == 4) {
                System.out.println();
            }
        }
        ++count;
    }
}
//returns lengthof int
static int countOf(int value) {
    int count = 0;
    while (value != 0) {
        value = value / 10;
        count++;
    }
    return count;
}

Upvotes: 0

Subito
Subito

Reputation: 36

That would work. Something like:

if((i + 1) % 5 == 0)
{System.out.print("\n");}

Upvotes: 0

iskandarchacra
iskandarchacra

Reputation: 368

for (int i = 0; i <256; i++ ){
        System.out.print( i + "\t" + (char)i + "\t");
        if(i % 5 == 0)
            System.out.println();

        ++count;
    }

This will number the characters and insert tabs between them. You will have 5 characters per line. \t is a tab.

Upvotes: 0

Bon
Bon

Reputation: 3103

Use Decimal format to format the numbers, use "\t" to print out the tab character.

public class UnicodeTable {

public static void main(String[] args) {
    final char Per_Line = 5;
    DecimalFormat format = new DecimalFormat("00000"); // format for the number
    for (int i = 0; i < 256; i++) {
        System.out.print(format.format(i) + "\t" + (char) i + "\t");// print a pair of number and its corresponding ascii character
        if ((i + 1) % Per_Line == 0) System.out.println();// change to a new line after printing five pairs
    }
}
}

A sample output:

enter image description here

Upvotes: 4

Related Questions