我在使用以下代码时遇到问题:
//Program 6.12
public class Ex6_12 {
public static void printChars(char ch1, char ch2, int numberPerLine) {
for (int i = ch1; i>ch2; i++) {
for (int j = 0; j<=numberPerLine; j++) {
System.out.printf("%c ", (char)(i));
}
System.out.println("");
}
}
public static void main (String[] args) {
printChars('1', 'Z', 10);
}
}
前面的代码不打印任何内容,我希望它以每行选定的字符数将选定的字符打印到不同的选定字符。不确定我在哪里犯了错误。
对于这个输入,我想要输出:
1 2 3 4 5 6 7 8 9 :
; < = > ? @ A B C D
E F G H I J K L M N
O P Q R S T U V W X
Y
(范围从传递的第一个 char
到小于最后一个,一行中的 char
数量与 numberPerLine
一样多>)
最佳答案
为此您不需要两个循环。由于您在内循环中使用 i
,但从不递增它,因此您会打印 numberPerLine
次相同的字母。只需检查 numberPerLine
的模数是否等于 numberPerLine - 1
(如果已打印 numberPerLine
元素):
public static void printChars(char ch1, char ch2, int numberPerLine) {
for (char i = ch1; i<ch2; i++) {
System.out.printf("%c ", i);
if((i-ch1) % numberPerLine == numberPerLine-1) {
System.out.println("");
}
}
}
这将给出:
1 2 3 4 5 6 7 8 9 :
; < = > ? @ A B C D
E F G H I J K L M N
O P Q R S T U V W X
Y
关于java - 使用循环打印 int 值中的字符,每行输出具有所需数量的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55112488/