循环打印输出并打印换行符

时间:2015-01-06 23:04:47

标签: java

我在java中编写了一个简单的程序来查找阶乘,这很好用。我现在正在尝试改进输出,但我不知道该怎么做。

我的计划:

import java.util.Scanner;

public class UserInput {

    public static void main(String[] args) {
        int fact = 1;

        Scanner number = new Scanner(System.in);
        System.out.println("Enter the number : ");
        int n = number.nextInt();
        if (n < 0) {
            System.out.println("Enter positive number");
        } else {
            System.out.print("Factorial Sequence is :");
            for (int i = n; i >= 1; i--) {
                fact = fact * i;
                System.out.print(i + "*");
            }

            System.out.println("Factorial of number " + n + " is :" + fact);
        }

    }
}

显示的输出采用此格式(单行,*后1):

  

因子序列是:5 * 4 * 3 * 2 * 1 * 5号因子是:120

我希望以这种格式输出:

  

因子序列为:5 * 4 * 3 * 2 * 1
  5号因子是:120

4 个答案:

答案 0 :(得分:3)

由于1不会修改因子结果,因此您的代码可以重写为:

        for (int i = n; i >= 2; i--) {
            fact = fact * i;
            System.out.print(i + "*");
        }
        System.out.println("1");

答案 1 :(得分:1)

要缩小差距,您可以添加\n字面值来表示换行符。

 System.out.println("\nFactorial of number " + n + " is :" + fact);

对于上一个*,您可以在结尾删除它,也可以在i为1时不添加它。

 System.out.print(i + (i > 1?"*":""));

这表示如果i大于1,则返回*,否则返回空字符串。

答案 2 :(得分:1)

另一种选择是在for循环期间使用字符串连接:

String s = "Factorial Sequence is :";
for (int i = n; i >= 1; i--) {
    fact = fact * i;
    s += i + (i > 1 ? "*" : "");
}
System.out.println(s);

只有&#39;受益&#39;这已经超过了其他选项,它以每次迭代的方式保存调用System.out.print,代价是字符串连接操作。可能根本没有性能差异,当然也没有显着性,但它是同一目的的另一种方式。

编辑:使用@ demostene的优秀建议,以避免最终的&#39; *&#39;决赛之后&#39; 1&#39; - 它避免了for循环中的条件表达式,这非常好,因为你的阶乘变大了。

答案 3 :(得分:0)

只需添加打印行声明:

System.out.println(); // add this line
System.out.println("Factorial of number " + n + " is :" + fact);
相关问题