【问题标题】:using JAVA Loop使用 JAVA 循环
【发布时间】:2021-06-14 09:48:29
【问题描述】:

编写一个从 5 到 500(包括 5 到 500)按 5 计数的应用程序,并且 在每 50 的倍数(50、100、150 等)之后开始一个新行。

如何移动到新行以打印 50 的倍数?

package loop2;

/**
 *
 * @author whitneykenny
 */
public class Loop2 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        
        int i = 5;
        while (i <=500) {
        
        System.out.print(i + " ");
        i = i + 5 ;
        
        }          
    }
}

【问题讨论】:

    标签: java loops newline


    【解决方案1】:

    这可能就是你要找的东西:

    public class Main {
        public static void main(String[] args) {
            int number = 5;
            while (number <= 200) {
                System.out.print(number + " ");
                if (number % 50 == 0) {
                    System.out.println();
                }
                number += 5;
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      为此,我会为这个问题使用 for 循环。 由于我假设您是初学者,因此我对所有内容都进行了评论,因此很容易理解。

      这是在移动设备上完成的,所以对格式感到抱歉。

      //set your variables
      Int maxnum = 500; //the value to count to
      Int NewLineAt =50; 
      
      //looks 500 times and starts at 5, adds 5 each loop
      For (int i = 5; i <= maxnum; i+=5)
      {
      
      //if your number divides into 50 with no remainder add
      //a new line with the "/n" which means new line
          If ( i % NewLineAt == 0)
          {
              System.out.print(i + "/n");
          }
      }
      

      【讨论】:

        【解决方案3】:

        使用 System.out.println() 代替 System.out.print();

        【讨论】:

          【解决方案4】:

          这是一个糟糕的格式问题吗?

          请将其格式化为一个易读的问题。

          然而,你需要的是

          if (i % 50 == 0) System.out.println();
          

          该代码将通过模运算符检查您是否已达到 50 步,如果是则打印新行

          【讨论】:

            猜你喜欢
            • 2012-10-22
            • 1970-01-01
            • 2018-05-27
            • 2013-08-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多