Reputation: 581
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();
}
}
}
Upvotes: 2
Views: 7006
Reputation: 799
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("");
}
}
Upvotes: 0
Reputation: 10500
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
Upvotes: 3
Reputation: 358
You could use the Modulo (%) Operator
if ( (c - 32) % 10 == 0)
System.out.print("\n");
Upvotes: 1
Reputation: 2823
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();
}
Upvotes: 1
Reputation: 675
Here's a condition that should work.
if((c - 31) % 10 == 0) { System.out.println(); }
Upvotes: 1