简体   繁体   中英

Java Factorial On JOptionPane

I want to show factorial result and work(calculation) in same JOptionPane dialog box, as example 1x2x3x4x5=120 and spent hours but haven't found a solution. Any help will be highly appreciated. :)

private fun uploadWithTransferUtility(remote: String, local: File) {
   String number = JOptionPane.showInputDialog("Please enter the number below ");

   int n = Integer.parseInt(number);
   long fact = 1;
    int i = 1;
    if (n<=0){
    JOptionPane.showMessageDialog(null," Please enter a possitive number");

    }
    else{

     while(i<=n)
    {


    if (i==1){
            fact = fact * i;
            System.out.print(i);
            i++;
        }
        else{
            fact = fact * i;
            System.out.print("*"+i);
            i++;
    }


    JOptionPane.showMessageDialog(null,"="+fact);   
}

You can do it like this

int n = Integer.parseInt(number);
long fact = 1;
int i = 1;
if (n <= 0) {
    JOptionPane.showMessageDialog(null, " Please enter a possitive number");
} else {
    StringJoiner stringJoiner = new StringJoiner("x"); //You can use "*" if you want
    for (i = 1; i <= n; i++) {
        fact = fact * i;
        stringJoiner.add(i + "");
    }

    JOptionPane.showMessageDialog(null, stringJoiner.toString() + "=" + fact);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM