是For循环内部还是外部的打印声明?

时间:2017-12-23 05:53:01

标签: java for-loop printing

我正在编写一个程序来计算阶乘,但似乎无法找出实际打印出最终值的部分。

import java.util.*;
public class Factorial {
public static void main(String[] args) {
    Scanner scan=new Scanner(System.in);
    System.out.println("Enter integer value: ");
    int x=scan.nextInt();
    System.out.print(x+"!=");
    int y=0;


    for(int i=x;i>0;i--) {
        //y=x*i;
        y=i*(i-1);

         if(i==1) 
        System.out.print(i+"=");

        else
            System.out.print(i+"*");
        //for (int j=2;j>=1

    }
    System.out.print(y);        
}
}

程序应该显示它乘以的数字

  

即。 INPUT = 5   OUTPUT = 5!= 5 * 4 * 3 * 2 * 1 = 120   要么   OUTPUT = 5!= 1 * 2 * 3 * 4 * 5 = 120

1 个答案:

答案 0 :(得分:0)

您需要做的第一件事就是将大括号括起来然后缩进,以减少混淆。 下面的代码执行您的意图并具有必要的注释

import java.util.*;

public class Factorial {

public static void main(String[] args) {
    Scanner scan=new Scanner(System.in);
    System.out.println("Enter integer value: ");
    int x=scan.nextInt();
    System.out.print(x+"!=");
    int y=1;// Initialize to 1 not 0 as you'll be multiplying.


    for(int i=x;i>0;i--) {

        /*
          Iteration by iteration:
          i = 5,y= 1-> y = 1*5
          i = 4,y= 5-> y = 5*4
          So on...
        */
        y*=(i);

         if(i==1) 
            {
                // Print Equal only if its the last number. Since 
                   we are going 5*4*3*2*1 =. We need this if to print
                   1 =.
                System.out.print(i+"=");

            }

        else
            {
                //For other cases just print Number and *.
                System.out.print(i+"*");

            }


    }
    // Print the actual output.
    System.out.print(y);        



}

}