我用Java创建了一个ASCII表,每行打印10个字符,然后来自'!'到'〜'。一切都很好,除了第一行,只打印九个字符(或打印一个空格?)。有没有人看到会导致这种情况的语法或处理问题?它只发生在第一行。 注意:我只允许使用一个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
答案 0 :(得分:1)
你的数学是正确的,因为它将决定在第10个字符上打印换行符(#42)。但是,在打印字符之前首先打印换行符,因此只有9个字符进入第一行。第10到第19个字符印在第二行等等。
在打印当前字符后移动换行符打印行和关联的if
语句。
此外,println
将在作为参数传递的字符串之后打印换行符。您只需拨打println()
。
答案 1 :(得分:0)
代码应该看起来像
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
因为您在第一行打印出第十个字符之前正在进入下一行。