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

   }
 }

}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Anthony J
  • 551
  • 1
  • 9
  • 19

5 Answers5

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
zb226
  • 9,586
  • 6
  • 49
  • 79
1

Here's a condition that should work.

if((c - 31) % 10 == 0) { System.out.println(); }
Gauthier JACQUES
  • 655
  • 5
  • 15
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();

}
thegauravmahawar
  • 2,802
  • 3
  • 14
  • 23
1

You could use the Modulo (%) Operator

if ( (c - 32) % 10 == 0)
  System.out.print("\n");
Sinic
  • 348
  • 3
  • 10
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("");
        }
    }   
Jure
  • 799
  • 6
  • 25
  • 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 – Anthony J Oct 09 '15 at 14:57
  • @AnthonyJ Check my answer, I changed pseudo code with Java code. – Jure Oct 12 '15 at 12:55