我必须以表格格式打印出Ascii码(每行10个字符…)
现在我让他们按顺序打印。但是我想打印10个字符,然后再打印10个……
我相信我应该能够用if(如果有10个字符,println…)语句来做到这一点,但我似乎无法弄清楚……的逻辑。
请帮…
我的代码:
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();
}
}
}
利用模运算符%
每10个字符添加一个换行符:
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();
}
}
}
输出: !"#$%&'()
*+,-./0123
456789:;<=
>?@ABCDEFG
HIJKLMNOPQ
RSTUVWXYZ[
]^_`abcde
fghijklmno
pqrstuvwxy
z
这里有一个条件。
if((c - 31) % 10 == 0) { System.out.println(); }
只需使用counter
来跟踪位置。当counter
能被10整除时,加一个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();
}
可以使用取模(%)运算符
if ( (c - 32) % 10 == 0)
System.out.print("n");
你就快成功了。只要把你的for循环放到另一个for循环中,它将运行10次(嵌套循环)。
那么你的程序将是这样的:
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("");
}
}