2

I've got to print out the Ascii codes in a table format (10 chars per row...)

At the moment I have them printing all in order. However I'd like to print 10 characters then println and print another 10...

I believe I should be able to do this with an if (if there are 10 chars, println...)statement, but I can't seem to figure out the logic of how..

Please help...

My code so far:

public class Ascii {

  public static void main (String[]args) {

   for (int c=32; c<123; c++) {

    System.out.print((char)c);

   // if(

  //System.out.println();

   }
 }

}

5 Answers 5

3

Leverage the modulo operator % to add a newline every 10 characters:

public static void main(String[] args) {
    for (int c = 32; c < 123; c++) {
        System.out.print((char) c);
        if ((c - 31) % 10 == 0) {
            System.out.println();
        }
    }
}

Output:

 !"#$%&'()
*+,-./0123
456789:;<=
>?@ABCDEFG
HIJKLMNOPQ
RSTUVWXYZ[
\]^_`abcde
fghijklmno
pqrstuvwxy
z
Sign up to request clarification or add additional context in comments.

2 Comments

This seems to be the most cleanest among all :)
My answer does exactly the same, and was posted a minute earlier :-)
1

Here's a condition that should work.

if((c - 31) % 10 == 0) { System.out.println(); }

Comments

1

Just use a counter to keep track of the position. Whenever the counter is divisible by 10 add a new line:

int count = 0;
for (int c = 32; c < 123; c++) {

  System.out.print((char)c);
  count++;
  if(count % 10 == 0)
    System.out.println();

}

Comments

1

You could use the Modulo (%) Operator

if ( (c - 32) % 10 == 0)
  System.out.print("\n");

Comments

0

You are almost there. Just put your for loop in another for loop which will run 10 times(nested loops).

So your program will be like this:

public static void main(String[] args) 
    {
        for (int c=33; c<123; c+=10) {
            for(int i = 0;i < 10; i++)
            {
                System.out.print((char)(c+i) + " ");
            }
            System.out.println("");
        }
    }   

2 Comments

This is what I wanted to do...a loop with a loop. Could you help hint me a little further, I'm still struggling with this one!...thanks
@AnthonyJ Check my answer, I changed pseudo code with Java code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.