0

I'm stumped on this - I wrote a try/catch for a helper method. It's purpose is to catch any invalid input (anything that is not "male" or "female" (no specific case). If the input is invalid, it will notify the user and then have them try again. If it is valid, the method will return the input.

When I run the program, it doesn't catch the invalid inputs. Why isn't this working?

Here's the helper Method:

//Helper method that gathers the string input from user
public static String getString() {

    //Create new scanner input
    Scanner input = new Scanner(System.in);

    //Declare and initialize variables
    String wordIn = "";
    boolean validIn;

    //do/while loop for obtaining input and checking validity (try/catch)
    do {
        validIn = true;
        try{
            wordIn = input.nextLine();

        //End Try   
        }

        catch(Exception invalidInput) {
            validIn = false;
            input = new Scanner(System.in);
            System.out.print("\nYou have entered an invalid input. Please "
                    + "enter either \"Male\" or \"Female\" ONLY for this "
                    + "selection. The selection is not case sensitive."
                    + "\n\nPlease enter your selection: ");

        //End Catch    
        }

    //While input is valid, return the input    
    } while (!validIn);
     return wordIn;

//End helper
}

Here's the code from the test:

//Obtain user input and print output
String passGender = getString();
System.out.println("\n" + titanic.getSurvivedPassengersGender(passGender)
                        + " " + passGender.toLowerCase() + " passengers survived the "
                        + "sinking of the Titanic.");

It seems as if I don't have a conditional set right...I can't find where I went wrong. I'm still new to this, so I'm sure it's a simple mistake. Any help is greatly appreciated. Thank you folks!

Atri
  • 5,511
  • 5
  • 30
  • 40
StevenC
  • 109
  • 1
  • 20
  • After `wordIn = input.nextLine();`, you need to check for its value. If it is invalid value then you need to throw an Exception which will be caught by the catch clause. – Atri Nov 19 '15 at 01:12
  • btw, why do you want to throw an exception, instead you could just have a condition. If input string is not "male" or "female", then you can execute the code you currently have in the `catch` clause – Atri Nov 19 '15 at 01:13
  • Yep - I'm a certified idiot now...It's been one long day. I can't believe I missed the fact that I didn't set a condition for what is valid. What a day! Sorry for wasting your time, thanks guys! – StevenC Nov 19 '15 at 01:19

2 Answers2

3

You didn't set any conditions for what you want. You didn't set any conditions for throwing on the event of an input that isn't 'male' or 'female'. your code should be:

//Helper method that gathers the string input from user
public static String getString() {

//Create new scanner input
Scanner input = new Scanner(System.in);

//Declare and initialize variables
String wordIn = "";
boolean validIn;

//do/while loop for obtaining input and checking validity (try/catch)
do {
    validIn = true;
    try{
        wordIn = input.nextLine();
        if(!(wordIn.equalsIgnoreCase("male") || wordIn.equalsIgnoreCase("female")))
            throw new Exception();
    //End Try   
    }

    catch(Exception invalidInput) {
        validIn = false;
        input = new Scanner(System.in);
        System.out.print("\nYou have entered an invalid input. Please "
                + "enter either \"Male\" or \"Female\" ONLY for this "
                + "selection. The selection is not case sensitive."
                + "\n\nPlease enter your selection: ");

    //End Catch    
    }

//While input is valid, return the input    
} while (!validIn);
 return wordIn;
//End helper
}

EDIT Also, like @ashutosh said, you don't have to throw an exception, you can just use a condition:

wordIn = input.nextLine();
if(!(wordIn.equalsIgnoreCase("male") || wordIn.equalsIgnoreCase("female"))
     System.out.print("\nYou have entered an invalid input. Please "
                + "enter either \"Male\" or \"Female\" ONLY for this "
                + "selection. The selection is not case sensitive."
                + "\n\nPlease enter your selection: ");
789
  • 718
  • 1
  • 10
  • 30
  • 1
    if(!(wordIn.equalsIgnoreCase("male") || wordIn.equalsIgnoreCase("female"))) because string equality doesn't work with = or != – Shobit Nov 19 '15 at 01:17
  • Don't know how on earth I missed that - other than the fact that I'm running on fumes. I feel like an idiot now. Thanks so much for letting me waste your time! – StevenC Nov 19 '15 at 01:18
  • it happens to all of us :) – 789 Nov 19 '15 at 01:23
  • @Shobit String equality does work with == and !=. Just that it works differently than `equals()` as described in http://stackoverflow.com/questions/767372/java-string-equals-versus – Atri Nov 19 '15 at 01:25
1

Or (as many said in comments) you should better use conditions instead. Something like:

wordIn = input.next(); 

while(!(wordIn.toLowerCase().equals("male") || wordIn.toLowerCase().equals("female"))){

System.out.println("\nYou have entered an invalid input. Please "
                + "enter either \"Male\" or \"Female\" ONLY for this "
                + "selection. The selection is not case sensitive."
                + "\n\nPlease enter your selection: ");
wordIn = input.next();

}

This will keep looping until valid string is entered without the need of try catch.

Jaskaranbir Singh
  • 2,034
  • 3
  • 17
  • 33
  • I understand, and agree. The only reason I'm using try/catch is to exercise what has been taught throughout the course that I'm taking. I was going to just keep it simple and go without the try/catch, but needed to include some more exceptions to show the full understanding. Thanks for your feedback though. – StevenC Nov 19 '15 at 01:27