2016-02-27 60 views
0

我的老师问我们创建了一个横跨10列的表格,并显示了从33到127的ASCII字符。我做错了什么,它都显示在一行?

我得到的字符,但他们都在一行。

我在做什么错?

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(" "); 
      } 
     } 
    } 
} 
+3

你从未打印新行... – Gaskoin

+0

不打印任何新行。 – khelwood

+0

使用'println'在每一行中打印结果。 –

回答

2

A newline从不打印。你可以做

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(); 
    } 
} 
+0

也可以做'如果(b%10 == 9)' – Clashsoft

+0

是啊,这是有道理的:) – Reimeus

0

正如其他人所指出的那样,你的代码是用System.out.print()代替System.out.println()你不是递增计数器变量b,这就是为什么该行分裂就不会工作,无论是。

下面是通过避免System.out.print/ln呼叫的环内,而是存储StringBuilder内的字符值,它的值,则程序退出之前打印最小化代码重复的溶液:

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