Java 使用循环从int值打印字符,每行输出所需的数字数
我在以下代码中遇到问题:Java 使用循环从int值打印字符,每行输出所需的数字数,java,Java,我在以下代码中遇到问题: //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
//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);
}
}
//程序6.12
公共类Ex6_12{
公共静态无效打印字符(字符ch1、字符ch2、整数行){
对于(int i=ch1;i>ch2;i++){
对于(int j=0;j?@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
一样多)您的printChars
方法中的第一个for
循环中存在逻辑错误。该循环应检查i是否小于要执行的ch2
。如果在调用该方法时执行了正确的参数,则当前循环将是无限循环
因此,我将这个
for
循环for(inti=ch1;I>ch2;I++)的更改为for(int i=ch1;i你不需要两个循环。因为你在内部循环中使用i
,但从不增加它,你会得到相同的字母打印numberline
次。只要检查一下numberline
的模数是否等于numberline-1
(如果已经打印了编号基线
元素):
publicstaticvoidprintchars(字符ch1、字符ch2、整数行){
对于(char i=ch1;i?@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
是'1'
大于或小于'Z'
?(提示:您希望
)它是以字符表示的acsii值,所以它更小。我相信Z在acsii中是90,1是1。它没有,它的值是49。程序在许多不同的表中返回11个相同的值。我如何解决这个问题?谢谢!将for(int i=ch1;i>ch2;i++)更改为for(inti=ch1;我非常感谢你!但是我如何让每个字符以一行中的字符数打印其中一个,作为numberline int?谢谢你!GBlodgett
已经指出了这一点。你可以使用这个技巧:如果((i-ch1)%numberline==numberline-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
//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);
}
}
//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);
}
}
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