简体   繁体   中英

What am I doing wrong, it all show up on one line?

My teacher asked that we create a table that is 10 columns across and shows the ASCII characters from 33 to 127.

I get the characters but they are all on one line.

What am I doing wrong?

public class ASCIICharacters {
    public static void main(String[]args) {
       char a,b=0;
       for (a=33;a<126+1;a++) {
           if(b%10==0) {
               System.out.print((Char)(a));
               System.out.print("   ");
           }
        }
    }
}

A newline is never printed. You could do

for (char a = 33, b = 0; a < 127; a++, b++) {
    System.out.print(a);
    System.out.print("\t");

    if (b % 10 == 9) {
        System.out.println();
    }
}

As others have pointed out, your code was using System.out.print() instead of System.out.println() and you weren't incrementing the counter variable b , which is why the row-splitting wouldn't have worked, either.

Here's a solution that minimizes code duplication by avoiding the System.out.print/ln calls within the loop and instead storing the character values inside a StringBuilder , value of which is then printed before the program exits:

 StringBuilder sb = new StringBuilder();
 char c = 33;
 for (int i = 1; c <= 127; c++, i++) {
     sb.append(c);

     if (i % 10 == 0) {
         sb.append("\n"); // newline every 10th character
     } else {
         sb.append("   "); // else append with a separator
     }
 }
 System.out.println(sb);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM