This question already has an answer here:
- Remove last separator from print statement 6 answers
- getting rid of last comma 4 answers
- Eliminating Last Comma & Space 6 answers
I'm trying to get rid of the asterisk (*) from the output on the last run of the for loop, it should print
5 * 4 * 3 * 2 * 1 is 120
But it actually prints
5 * 4 * 3 * 2 * 1 * is 120
can anyone help me out?
public static void getFactorial(){
Scanner sc = new Scanner (System.in);
int number = 0;
int factorial = 1;
int count;
System.out.println("Welcome to option 2 " + yourName + ": Calculate a factorial.");
System.out.println("Enter a number: ");
number = sc.nextInt();
System.out.println();
if (number > 0)
{
for (count=number; count>0; count--) //count starts same as number, loops until it gets to 1
{
if(count > 1)
factorial = factorial*count;
System.out.print(count + " * ");
if(count == 1)
System.out.print(" is "+factorial);
System.out.print("");
}
}
else if (number<=0)
{
System.out.println("Please enter a number greater than 0.");
}
else
{
System.out.println("Please enter a whole number");
}
Aucun commentaire:
Enregistrer un commentaire