0

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");
     }
}
Community
  • 1
  • 1
Smith
  • 1
  • Don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels Oct 10 '16 at 21:22
  • So instead of, `while (answer == "Yes");` do something like: `while (answer.equalsIgnoreCase("yes"));` – Hovercraft Full Of Eels Oct 10 '16 at 21:22
  • Thank you, it works now! – Smith Oct 10 '16 at 21:43

0 Answers0