0

I wrote this code so that if the user press enter then it will throws the custom exception other wise it will return the user entry. But this code is throwing the custom exception anyway weather it is blank or string when I first run this code.Dont know how to fix this.

public static String validEmpty(Scanner sc, String prompt)
{
    String userEntry = null;
    Boolean isValid  = true;

    while (isValid)
    {
        System.out.print(prompt);
        try 
        {
            if ((userEntry=sc.nextLine()).isEmpty())
                throw new CustomException();
            else
                return userEntry;
        }
        catch (InputMismatchException e)
        {
            sc.nextLine(); 
            System.out.println("Error! Name must be alphabets only!");
        }
        catch (CustomException e)
        {
            sc.nextLine(); 
            System.out.println("Error! Entry Cannot Be blank!");
        }
    }
    return userEntry;
}
grovesNL
  • 5,534
  • 2
  • 18
  • 31
  • 1
    did you try removing line endings `str=str.replace("\r","").replace("\n","");` – washcloth Nov 11 '14 at 01:04
  • have you stepped thru the code.. also take a look at the previous stackoverflow posting to give you some alternatives http://stackoverflow.com/questions/136035/catch-multiple-exceptions-at-once also is this a Java App or C# winforms or C# Console application..? – MethodMan Nov 11 '14 at 02:07
  • *"this code is throwing the custom exception [...] when I first run this code"* This is a symptom of you calling a Scanner method like `nextInt` prior to calling `nextLine`. http://stackoverflow.com/a/13102066/2891664 If that Q&A does not help you solve your problem you should provide us an [MCVE](http://stackoverflow.com/help/mcve). – Radiodef Nov 11 '14 at 02:11
  • Yes I tried that but it didn't work. – loftywaif002 Nov 11 '14 at 02:11
  • Try replacing `if((userEntry=sc.nextLine()).isEmpty())` with `if(!scanner.hasNextLine())` and `else return userEntry=scanner.nextLine()` – Dinal24 Nov 11 '14 at 02:43
  • Tried that, well, this code works only if the user input is String type.But if the user press just enter, then it wont work. If I write next() instead of nextLine() then it will work as the same way as your code. My goal is if the user input is blank, then it will throw Xustome exception. but if there is a String, then it will just return it and other way around as well. – loftywaif002 Nov 11 '14 at 07:51

0 Answers0