[英]Missing character in ASCII table - Java
我用Java创建了一个ASCII表,该表每行打印10个字符,从'!'开始。 到“〜”。 除了第一行只打印9个字符(或打印空格?)外,其他所有东西都运行良好。 是否有人看到会导致这种情况的语法或处理问题? 它只发生在第一行。 注意:只允许我使用一个for循环。
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
您的数学是正确的,因为它将决定在第10个字符上打印换行符(#42)。 但是,在打印字符之前,先打印换行符,因此只有9个字符将其换行到第一行。 第10至19个字符打印在第二行等上。
在打印当前字符之后,移动换行符打印行和关联的if
语句。
同样, println
在将字符串作为参数传递之后已经已经打印了换行符。 您可以只调用println()
。
代码应该看起来像
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
因为您当前要在下一行输出之前在第一行上打印出第十个字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.