【问题标题】:Prevent trailing character when printing values in a loop [duplicate]在循环中打印值时防止尾随字符[重复]
【发布时间】:2020-12-03 10:52:03
【问题描述】:

我的任务是为 Java 解决循环问题,但我目前在如何显示数字的阶乘方面遇到问题。例如,1x2x3x4x5 = 120。

我快到了,但我似乎无法弄清楚如何,或者是否有任何可能的方法来显示数字的阶乘,因为在 5 的末尾总是有一个额外的“x”。

这是我的代码:

import java.util.*;
public class trylangpo2 {

    public static void main(String[] args) {
        Scanner input = new Scanner (System.in);
        int fctr;
        System.out.println ("number");
        fctr = input.nextInt();
    
        for (int i = 1; i <=fctr; i++){
            System.out.print(i);
    
            int j;
            for (j =1; j <=1 ; j++){
                System.out.print("*");
            }
        }
    }   
}

示例输出:

1x2x3x4x5x

【问题讨论】:

  • 是否存在因子流行病? stackoverflow.com/questions/65089542/…
  • 没有解决您的问题,只是指出您的循环 for (j =1; j &lt;=1 ; j++) 可以删除。它只循环一次,只需写System.out.print("*");。不需要循环

标签: java


【解决方案1】:

如果条件不在循环末尾,请尝试添加条件。然后添加开始,如果是结束,则打印数字:

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int fctr;
    System.out.println("number");
    fctr = input.nextInt();

    for (int i = 1; i <= fctr; i++) {
        if (i < fctr) {
            System.out.print(i + " * ");
        } else {
            System.out.print(i);
        }
    }
}

【讨论】:

    【解决方案2】:

    我总是使用类似的结构

    String sep="";
    for (...) {
       System.out.print(sep);
       System.out.print(payload);
       sep="x";
    }
    

    【讨论】:

      【解决方案3】:

      可以删除(j =1; j &lt;=1 ; j++) 的循环。它只循环一次,只需写System.out.print("*")。无需循环

      那么如果你考虑一下,你想一直打印数字和*,除非它是最后一个数字(fctr

      那就这样写吧:

      Scanner input = new Scanner (System.in);
      int fctr;
      System.out.println ("number");
      fctr = input.nextInt();
      
      for (int i = 1; i <=fctr; i++){
          System.out.print(i);
      
          if(i<fctr) {
              System.out.print("*");
          }
      }
      

      【讨论】:

        【解决方案4】:

        您需要打印 ***** 条件。如果i == fctr,请勿打印 *****。而且您不需要j 的额外循环。如下:

            public static void main(final String[] args) {
            final Scanner input = new Scanner(System.in);
            int fctr;
            System.out.println("number");
            fctr = input.nextInt();
        
            //    IntStream.range(1, fctr).
        
            long factorial = 1;
            for (int i = 1; i <= fctr; i++) {
              factorial = factorial * i;
              if (i == fctr) {
                System.out.print(i);
              } else {
                System.out.print(i + "*");
              }
            }
        
            System.out.print("=" + factorial);
          }
        

        【讨论】:

          猜你喜欢
          • 2011-11-07
          • 2020-10-27
          • 2021-04-22
          • 2017-06-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多