I'm having some trouble with the following Java code using Scanner in a do-while loop. The code is supposed to compute the value of a factorial requested by the user, and then ask the user if he/she wants to compute another factorial. If they say Yes, then the loop runs again, if No, then the loop exits.
On the first iteration, everything runs smoothly. However, when it asks if I want to compute another number, although I enter "Yes", it does not run again. I read here that adding a nextLine() to clear the \n might help, but I can't seem to get it to work -- any tips?
import java.util.*;
public class Factorial
{
public static void main(String[] args)
{
Scanner kbscanner = new Scanner(System.in);
String answer;
do
{
// get the value from the user
System.out.print("\nEnter a Number: ");
int number = kbscanner.nextInt();
// compute factorial
int factorial = 1;
for (int i = 1; i <= number; i++)
factorial *= i;
// display factorial
System.out.println("The value of " + number + "! is " + factorial);
// ask if user wants to calculate another factorial
System.out.print("Would you like to calculate another number? ");
kbscanner.nextLine(); // gets rid of the \n from when nextInt was asked
answer = kbscanner.next();
} while (answer == "Yes");
System.out.println("End");
}
}