2 回答

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超13個(gè)贊
為此,您不需要兩個(gè)循環(huán)。由于您在內(nèi)部循環(huán)中使用,但從不增加它,因此您將獲得相同的字母打印時(shí)間。只需檢查一下,看看 的模量是否等于(如果有打印的元素):inumberPerLinenumberPerLinenumberPerLine - 1numberPerLine
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

TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超3個(gè)贊
方法中的第一個(gè)循環(huán)中存在邏輯錯(cuò)誤。循環(huán)應(yīng)檢查是否要執(zhí)行。如果在調(diào)用方法時(shí)執(zhí)行正確的參數(shù),則當(dāng)前參數(shù)將是無限循環(huán)。forprintCharsi is less than ch2
所以,我把這個(gè)循環(huán)改成了,正如你可能已經(jīng)猜到的那樣,它是有效的。而且,如果你想打印包括最后一個(gè)字符,那么你需要檢查直到相等forfor (int i = ch1; i>ch2; i++)for (int i = ch1; i<ch2; i++)for (int i = ch1; i<=ch2; i++)
//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);
}
}
打印包括最后一個(gè)字符:
//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);
}
}
添加回答
舉報(bào)