-4

I'm new to Java (actually only on my third day) but enjoy pushing myself when it comes to learning a new bit of code, I did the same when learning MATLAB as part of my Degree. In essence I like going one step further than what each particular lesson is trying to teach.

I am currently writing a basic Calculator that can add, subtract, multiply and divide two numbers and have that core element working correctly. My "one step further" in this case was to make the program repeating with the option to exit via user input and to prevent any errors due to invalid user inputs.

I have been able to complete the repeating and exiting sections of this little project but have been unable to prevent errors caused by invalid user inputs, namely those caused by a String being inputted instead of the desired Int or Double. My goal is to prevent the error and instead ask for a valid input.

From what I have gathered, my problem can be addressed through the use of a Try/Catch Statement but I have no idea how to implement such a statement correctly. My best attempts, following similar-ish examples online have been met with failure, which I think is simply down to the way I have coded the program itself. As I said, I am new and have used lots of While Loops to achieve the desired behaviour and this is probably a horribly inefficient way of doing things.

Hopefully someone is able to point me in the right direction,
Conor

My best attempt thus far:

int InputValue;
InputValue = 1;
while (InputValue == 1)
{
    try
    {
        System.out.print ("Enter First Number: ");
        First = Input.nextDouble ();
        InputValue = 0;
    }
    catch (NumberFormatException e)
    {
        System.out.println ("Invalid Input");
        System.out.println (" ");
        System.out.print ("Enter First Number: ");
        First = Input.nextDouble ();
    }
}

But as stated above, this seems to make "First" invisible to the remainder of my code with the error:
"The local variable First may not have been initialized"

Also tried:

int InputValueX;
InputValueX = 1;
do
{
    System.out.println (" ");
    System.out.print ("Enter First Number: ");
    while (!Input.hasNextDouble ())
    {
        System.out.println ("Invalid Input");
        Input.next ();
    }
    First = Input.nextDouble ();
    InputValueX = 0;
}
while (InputValueX == 1);

This allows the code to run but does not address the invalid input error.

And I don't think I can use a Boolean as that is what is looping my entire program (or can you use multiple Boolean? I tried that and got errors)

http://pastebin.com/TTuCNQbx
- My Program, just over 100 lines long
- Area of interest between ~ 45 and 85

Infernox CJC
  • 21
  • 1
  • 1
  • 3
  • There are tons of tutorials out there :) Please come back once you have tried them and IF you still stuck and let us help you then. Use google first. – B001ᛦ Aug 09 '16 at 12:21
  • Possible duplicate of [Validating input using java.util.Scanner](http://stackoverflow.com/questions/3059333/validating-input-using-java-util-scanner) – xenteros Aug 09 '16 at 12:22
  • I obviously didn't explain well enough in the post but I have used Google and found a few similar examples in this very forum. However when I attempted to follow a similar process to those (using Try/Catch) it effectively broke any code after this section. The best way to describe it was that I used the Try/Catch on the Variable "First" and then any code following that Statement couldn't find "First" – Infernox CJC Aug 09 '16 at 12:25

3 Answers3

0
boolean firstNumber = false;
while (!firstNumber) {
    try {
        First = Input.nextDouble ();
        firstNumber = true;
    } catch (InputMismatchException e) {
        firstNumber = false;
        Input.nextLine();
    }
}

This should loop until a a proper Input was entered. I would recommend adding some System.out output to let the user know, that his input was invalid, and how a propper input might look like.

thorwinn
  • 113
  • 2
  • 8
0

Actually every user inputs Strings. Then You have to validate the String if it's acceptable format for you or not.

Let's assume you already have user's input stored in String input:

String input;
//some code for getting the input
try {
    double dbl = Double.parseDouble(input);
} catch (NumberFormatException e) {
    e.printStackTrace();
}

This is the general construction for parsing String into double. Now you can wrap it into a loop which would scan the input until you would find what you wanted. Feel free to use flags e.g.

boolean found = false;
try {
    double dbl = Double.parseDouble(input);
    found = true; //this line won't be executed if parsing fails
} catch (NumberFormatException e) {
    e.printStackTrace();
    found = false;
}
xenteros
  • 14,275
  • 12
  • 47
  • 81
  • the "found = false" in the catch block is not necessary, because found will remain false when an exception is thrown, like you said correctly :) – Willi Mentzel Aug 09 '16 at 12:52
  • @progressive_overload I know, but I've placed it there in case the OP modifies the code – xenteros Aug 09 '16 at 12:53
0

Surround the lines like Input.next* in your code with try/catch block. Catch the RuntimeException or in particularly InputMismatchException (best practice) like below,

    boolean Run = true;
    while (Run)
    {
        Scanner input = new Scanner (System.in);
        int i = 0;
        try
        {
            i = input.nextInt();
        }
        catch(InputMismatchException ime)
        {
            System.out.println("message to enter the input in valid format");
        }
    } 
Willi Mentzel
  • 21,499
  • 16
  • 88
  • 101
BSM
  • 131
  • 13