使用循环从 int 值打印字符,每行输出具有所需数字数

我在使用下面的代码时遇到问题:


//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

(它的范围从第一个通过,到小于最后一个,一行中有多少个charcharnumberPerLine)


拉丁的传说
浏览 107回答 2
2回答

开满天机

为此,您不需要两个循环。由于您在内部循环中使用,但从不增加它,因此您将获得相同的字母打印时间。只需检查一下,看看 的模量是否等于(如果有打印的元素):inumberPerLinenumberPerLinenumberPerLine - 1numberPerLinepublic static void printChars(char ch1, char ch2, int numberPerLine) {&nbsp; &nbsp; &nbsp;for (char i = ch1; i<ch2; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.printf("%c ", i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if((i-ch1) % numberPerLine == numberPerLine-1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;}这将给予:1 2 3 4 5 6 7 8 9 :&nbsp;; < = > ? @ A B C D&nbsp;E F G H I J K L M N&nbsp;O P Q R S T U V W X&nbsp;Y&nbsp;

蛊毒传说

方法中的第一个循环中存在逻辑错误。循环应检查是否要执行。如果在调用方法时执行正确的参数,则当前参数将是无限循环。forprintCharsi is less than ch2所以,我把这个循环改成了,正如你可能已经猜到的那样,它是有效的。而且,如果你想打印包括最后一个字符,那么你需要检查直到相等forfor (int i = ch1; i>ch2; i++)for (int i = ch1; i<ch2; i++)for (int i = ch1; i<=ch2; i++)//Program 6.12public class Ex6_12 {&nbsp; &nbsp; public static void printChars(char ch1, char ch2, int numberPerLine) {&nbsp; &nbsp; &nbsp; &nbsp; for (int i = ch1; i < ch2; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int j = 0; j <= numberPerLine; j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.printf("%c ", (char) (i));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; printChars('1', 'Z', 10);&nbsp; &nbsp; }}&nbsp;&nbsp;打印包括最后一个字符://Program 6.12public class Ex6_12 {&nbsp; &nbsp; public static void printChars(char ch1, char ch2, int numberPerLine) {&nbsp; &nbsp; &nbsp; &nbsp; for (int i = ch1; i <= ch2; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int j = 0; j <= numberPerLine; j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.printf("%c ", (char) (i));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; printChars('1', 'Z', 10);&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java