0

I created an ASCII table in Java that prints 10 characters per line, and goes from '!' to '~'. Everything worked great except for the first row, which only printed nine characters (or printed a space?). Does anyone see a syntax or processing problem that would be causing this? It only happened on the first row. Note: I was only allowed to use one for loop.

public class AsciiChars {

    public static void main(String[]args) {

        int count = 0; // initialize counter variable

        for (int ascii = 33; ascii < 127; ascii++, count++) { //conditions for the for loop

            if ((ascii - 12) % 10 == 0){ //formula needed to create the rows. The end char in each row,
                                         // minus 12 (42, 52, 62, etc), will be divisible by 10, thus ending the row.
            System.out.println("\n"); // Print a new line after every row.
        } //end if
            System.out.print((char)ascii + " "); //casting the ascii int to a char and adding a space after every char
        }//end for loop
    }//end main
}//end class
1
  • What were you expecting to see? Commented Feb 22, 2015 at 5:16

2 Answers 2

1

Your math is correct in that it will decide to print a newline character on the 10th character (#42). However, you print the newline first, before you print the character, so only 9 characters made it to the first line. The 10th through 19th characters are printed on the second line, etc.

Move the newline printing line and associated if statement after the print of the current character.

Also, println will already print a newline character after the string it's passed as a parameter. You can just call println().

Sign up to request clarification or add additional context in comments.

2 Comments

I should have known better with not needing the "\n" in the print statement. It was 4am while I was coding it up. Haha.
But yes, that was a syntactical oversight on my part with having the new line before the char print. That fixed it. I appreciate your help @rgettman
0

Code should look like

for (int ascii = 33; ascii < 127; ascii++, count++) { //conditions for the for loop

    System.out.print((char)ascii + " "); //casting the ascii int to a char and adding a space after every char

    if ((ascii - 12) % 10 == 0){ //formula needed to create the rows. The end char in each row,
                                 // minus 12 (42, 52, 62, etc), will be divisible by 10, thus ending the row.
        System.out.println("\n"); // Print a new line after every row.
    } //end if
}//end for loop

Because you are currently going to the next line before printing out the tenth character on the first line.

Comments

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.