【问题标题】:Printing characters (Ascii) in a row/table format with a for loop and if statement?使用for循环和if语句以行/表格式打印字符(Ascii)?
【发布时间】:2015-10-09 11:32:08
【问题描述】:

我必须以表格格式打印出 Ascii 代码(每行 10 个字符...)

目前我让它们按顺序打印。但是我想打印 10 个字符,然后 println 再打印 10 个...

我相信我应该能够用 if(如果有 10 个字符,println...)语句来做到这一点,但我似乎无法弄清楚如何......

请帮忙...

到目前为止我的代码:

public class Ascii {

  public static void main (String[]args) {

   for (int c=32; c<123; c++) {

    System.out.print((char)c);

   // if(

  //System.out.println();

   }
 }

}

【问题讨论】:

    标签: java loops for-loop ascii


    【解决方案1】:

    利用模运算符 % 每 10 个字符添加一个换行符:

    public static void main(String[] args) {
        for (int c = 32; c < 123; c++) {
            System.out.print((char) c);
            if ((c - 31) % 10 == 0) {
                System.out.println();
            }
        }
    }
    

    输出:

     !"#$%&'()
    *+,-./0123
    456789:;<=
    >?@ABCDEFG
    HIJKLMNOPQ
    RSTUVWXYZ[
    \]^_`abcde
    fghijklmno
    pqrstuvwxy
    z
    

    【讨论】:

    • 这似乎是最干净的:)
    • 我的回答完全一样,而且是在一分钟前发布的 :-)
    【解决方案2】:

    这是一个应该有效的条件。

    if((c - 31) % 10 == 0) { System.out.println(); }
    

    【讨论】:

      【解决方案3】:

      只需使用counter 来跟踪位置。每当 counter 可以被 10 整除时,添加 new line

      int count = 0;
      for (int c = 32; c < 123; c++) {
      
        System.out.print((char)c);
        count++;
        if(count % 10 == 0)
          System.out.println();
      
      }
      

      【讨论】:

        【解决方案4】:

        您可以使用模 (%) 运算符

        if ( (c - 32) % 10 == 0)
          System.out.print("\n");
        

        【讨论】:

          【解决方案5】:

          你快到了。只需将您的 for 循环放在另一个 for 循环中,该循环将运行 10 次(嵌套循环)。

          所以你的程序会是这样的:

          public static void main(String[] args) 
              {
                  for (int c=33; c<123; c+=10) {
                      for(int i = 0;i < 10; i++)
                      {
                          System.out.print((char)(c+i) + " ");
                      }
                      System.out.println("");
                  }
              }   
          

          【讨论】:

          • 这就是我想要做的……一个带循环的循环。你能帮我进一步提示一下吗,我还在努力解决这个问题!...谢谢
          • @AnthonyJ 检查我的答案,我用 Java 代码更改了伪代码。
          猜你喜欢
          • 1970-01-01
          • 2017-07-31
          • 2013-04-04
          • 2019-09-07
          • 2013-02-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-06-18
          相关资源
          最近更新 更多