Reputation: 1
Hey I am really new to java and need a little help with this please.
I have some basic code that works fine it calculates the factor of a number lets say 5 and it gives the output answer of in this case "Factorial = 120.00"
That's great but I want it to give me the output like this "5 * 4 * 3 * 2 * 1 = 120.00" but I just can't figure out how to do it.
Thanks for any help
public static void main(String[] args)
{
Scanner kboard = new Scanner(System.in);
int nos1=0;
int total=1;
DecimalFormat df = new DecimalFormat("#.00");
System.out.print("Please enter number to factor ");
nos1 = kboard.nextInt();
for (int x=1;x<=nos1;x++)
{
total = total *x;
}
System.out.println("Factorial = "+df.format(total));
}
Upvotes: 0
Views: 181
Reputation: 10947
String s = "";
for (int x = nos1; x >= 1; x--) {
total = total * x;
// print here it will work
if(!s.isEmpty())
s+="*";
s += x;
}
System.out.println(s + "=" + df.format(total));
Upvotes: 1
Reputation: 31184
This will only get you part of the way there.
this code will print
1 * 2 * 3 * 4 * 5 * = 120
for (int x=1;x<=nos1;x++)
{
System.out.print(x + " * ");
total = total *x;
}
System.out.println(" = " + df.format(total));
I'll let you figure out a way to print it in the order you want and get rid of the last * at the end. there are a few ways.
Upvotes: 1