import java.util.*;
import java.text.*;

public class FactorialApp
{
    public static void main(String[] args)
    {


        // create a Scanner object named sc and intializ variables


        Scanner sc = new Scanner(System.in);

        // perform Factorial application when user enters "y" or "Y"
        String choice = "y";
        while (choice.equalsIgnoreCase("y"))
        {
            //get input from user
            int power = getIntWithinRange(sc,
            "Enter number greater than 0 and less than 20: ", 0, 21);
            long number = 1;
            //use a for loop to calculate the power
            for (int i = 1; i<= power; i++)
            {

                   number = number * i;
             }
                   System.out.println("The factorial is: " + number + "\n");
                   String cont = "";
                   System.out.print("Continue? (y/n)");
                   cont = sc.next();
                   sc.nextLine();
                   System.out.println();


         }
}
public static int getInt (Scanner sc, String prompt)
{
    int i = 0;
    boolean isValid = false;
    while (isValid == false)
    {
        System.out.print(prompt);
        if (sc.hasNextInt())
        {
            i = sc.nextInt();
            isValid = true;
        }
        else
        {
            System.out.println
            ("Error! Invalid integer value. Try again.");
        }
        sc.nextLine(); //discard any other data entered on the line
    }
    return i;
}
    public static int getIntWithinRange (Scanner sc, String prompt, int min, int max)
    {
        int i = 0;
        boolean isValid = false;
        while (isValid == false)
        {
            i = getInt(sc, prompt);
            if (i <= min)
                System.out.println("Error! Number must be greater than " + min + ".");

            else if (i >= max)
            System.out.println("Error! Number must be less than " + max + ".");

            else
            isValid = true;
        }
        return i;
    }
  }//end program

I Only want to accept “y/Y” or “n/N” from the user for the continue prompt (i.e., include validations for the String as well as the numeric input)

Recommended Answers

All 8 Replies

Use a do {} while (); loop.

Pseudo-code:

String input;
do {
input = getInputFromUser();
} while (input != 'n' && input != 'y' && input != 'Y' && input != 'N');
doWhatEverYouWant();

Use a do {} while (); loop.

Pseudo-code:

String input;
do {
input = getInputFromUser();
} while (input != 'n' && input != 'y' && input != 'Y' && input != 'N');
doWhatEverYouWant();

ignore this answer.

the logic might look correct, but, and here 's a very big but, the '==' and '!=' operators can't be used to compare the values stored in Objects. if you want to compare the value of your String against one of the valid options, you'll have to use the .equals method.

String is a big exception to that. I know objects need to be compared using .equals(), but strings can always be compared directly. Please name an example where it can't!

String is not an exception.
As for every other class == tests for two objects being the same object and equals(...) tests for two objects being equivalent as defined by the author of the class. If you are deriving Strings from an expression and comparing them with String constants in your program you must use equals, not ==. For example:

String s1 = "A", s2 = "a";
      System.out.println(s1 == s2.toUpperCase()); // prints false
      System.out.println(s1.equals(s2.toUpperCase())); // prints true

ps @hiddenpolen: while (input != 'n'... In Java 'n' is a char not a String. Strings and chars are not comparable with == or != Even if you replace this with "n" you have a perfect example of why you have to use equals(...)

I understand: I actually did not know that. Ive always compaired strings like this, with no errors. I'll look into this, and sorry for the wrong answers.

I understand: I actually did not know that. Ive always compaired strings like this, with no errors. I'll look into this, and sorry for the wrong answers.

well ... you cán compare strings using ==, but, this will not compaire the value of the String objects, but the memory where it's allocated.
so in some cases, you will get the result you want, but if you try in a bit more complex code, you'll quickly see that that sure is not always the case

Ive always compaired strings like this, with no errors

The compiler is very smart about optimising String constants, so, for example, if you have
String s1 = "ABC";
then somewhere else
String s2 = "ABC";
the compiler will not create a second String, but will re-use the first String object (not the String reference!). In cases like that s1 == s2.
Optimisations like these are the reason that == sometimes works, but it's not part of the language spec, and you can't rely on it. equals(String other) is the only safe way.

Great info! I'll use equals() in the future!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.