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