Stopping/Resetting a Function in Java if Validation Criteria is not met - java

I am using this function below to check a value entered in a textbox and if it's valid under the try catch criterias, the function should return a True via the boolean Variable. The program is set up so the final calculation only happens if all my inputs come back as being OK or true in this case.
What I need to get working properly is the return for the try, if the number is not valid the function should stop and get the user to try again, I'm thinking of something like an Exit Sub from VB. My searches have turned up to use a return like I have below, but that just causes an error since the compiler thinks I am trying to return a function result.
There is a tiny bit more to the function, but I cut it out since it is irrelevant; it's pretty much just the bGarage = true; and return bGarage;.
public boolean fnGarageLevel() {//Beginning of Garage Validation Function
int nGarage;
boolean bGarage;
try {//Garage Number Validation Try
nGarage = Integer.parseInt(tfGarage.getText());
if (nGarage != 1 || nGarage != 2 || nGarage != 3 || nGarage != 4) {
JOptionPane.showMessageDialog( null,
"Enter a valid Garage Level, 1, 2, 3 or 4",
"Error",
JOptionPane.ERROR_MESSAGE);
tfGarage.setText("");
tfGarage.grabFocus();
return;
}//End of Error Message
}//End of try
catch (NumberFormatException nfe) {//Beginning of Catch
JOptionPane.showMessageDialog(null,
"Value Entered for Garage is not a Number",
"Error",
JOptionPane.ERROR_MESSAGE);
tfGarage.setText("");
tfGarage.grabFocus();
}//End of Catch for Garage field
bGarage = true;
return bGarage;
}//End of Garage Function

When the try section finishes its running successfully (that is, without catching any exception), the control goes right to the end of catch section or (if it exists) enters the section finally. In this case, the control jumps to bGarage=true sentence when the try ends. Remove the return; statement, it's not necessary.

Related

while loop parsing Double.IsNaN improperly

Language: Java, IDE: eclipse mars
The program is supposed to prompt the user (using JOptionPane) for a positive value. I'm trying to catch the invalid entries. My while statement catches the negative numbers but not the strings. When a negative number is entered, the prompt is shown again, but when a string value is entered, the exception is caught and the program moves on (when it should re prompt the user).
Once a positive value has been entered, the program assigns it to a value in another class. (We're learning the MVC OOP design pattern).
Double.isNaN(Double.parseDouble(h)) ---> can anyone help me find what am I missing?
// prompt to get bandwidth from user
// check for validity
// if invalid, prompt again
try{
h = JOptionPane.showInputDialog("Enter bandwidth as a positive number");
// loop until parsed string is a valid double
while (Double.isNaN(Double.parseDouble(h)) || Double.parseDouble(h) <=0) {
h = JOptionPane.showInputDialog("Enter bandwidth as a positive number");
}
// h has been set to valid double, set it to bandwidth
model.setBandwidth(Double.parseDouble(h));
}catch(NumberFormatException|NullPointerException NFE){
System.err.println("Caught exception: " + NFE.getMessage());
}
This is because of how parseDouble() works.
Throws:
NumberFormatException - if the string does not contain a parsable double.
(See here)
So if the String is not a double parseDouble() will not return NaN but throw an exception, which means your catch clause will be called.
To solve this problem maybe use recursively algorithm which will call your method again if an exception is thrown.
As 4castle already stated, you need to move your try/catch block inside your while loop.
However, for validating user input you can basically stick to the following pattern:
public Foo getUserInput() {
Foo result;
do {
try {
String s = requestUserInput(); // something like Scanner.nextLine()
result = parseUserInput(s); // something like Double.parseDouble(String)
}
catch(Exception exc) {
// maybe you want to tell the user what's happened here, too
continue;
}
}
while(!isValid(result)); // something like (0 < result)
return result;
}

Unreachable Code on openURL

case "Runetrack":
String inputValue1 = JOptionPane
.showInputDialog("Please enter your username");
if (inputValue1.length() == 0)
JOptionPane.showMessageDialog(null, "You must enter a username.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
openUrl("example.com/" + inputValue1);
break;
For some reason it's telling me that the openUrl(""); isn't 'Unreachable Code'. Why and how do I fix this, thanks.
Looking at the code logic, I'm guessing that the error message and the return are conditional. They need to be put inside the flower braces {} which constitute a code block and in your code, the code block for the if statement.
if (inputValue1.length() == 0) { // if block starts
JOptionPane.showMessageDialog(null, "You must enter a username.",
"Error", JOptionPane.ERROR_MESSAGE);
return;
} // if block ends
openUrl("example.com/" + inputValue1);
break;
The error you're getting is because, any code statement after a return statement will not execute the control is returned back to the calling method. Since the return wasn't conditional(in the code you posted), the 2 lines of code after that became unreachable, thereby giving the error you see. Once you put that inside the if conditional block, it'll work just fine.
You already called return, meaning that the execution pointer jumps out of the method. Therefore the code after the return call cannot be executed.
Edit: Maybe you just forgot to add { and } around the corresponding code.

Validation is working too well

I have this validation to check that user input is not blank and is only letters. If it's blank, it catches it, and if if includes digits it also catches it. If I input the 2 characters it asks for, however, it doesn't go through. I'm not sure how to go about this.
private static boolean isValidSt(String aSt) {
boolean result = false;
try {
if (aSt.length() == 2) {
result = true;
} else if (aSt.length() != 2) {
result = false;
}
for (int i=0; i <aSt.length();){
if (!Character.isLetter(i));{
return false;
}
}
return true;
} catch (NumberFormatException nfex) {
if (aSt == null) System.exit(0);
} catch (Exception ex) {
if (aSt == null) System.exit(0);
}
return result;
}
One problem that I can see right of the bat is this:
if (!Character.isLetter(i));{
return false;
}
That semi-colon after your if does not belong there. After checking your conditional statement, if it was true, it will execute until the semi-colon. The return false; isn't part of the if and will ALWAYS be executed.
As David Wallice rightly pointed out, you also never increment the counter in your for-loop, so were it not the case that the program always returned with false in the first iteration, it would indeed get stuck in an eternal loop. A very commonly used syntax for for-loops would be:
for(int i = 0; i < string.length(); i++) { }
A third and final note from me, this time nothin that would give an error, just good form:
You use System.exit(0); to exit the program as result of an exception. The zero you pass as an argument is usually only used when the program shuts down normally. This is a crash as a result of an error, so I'd use 1 or something.
Well, you could use StringUtils methods, isBlank and isAlpha, for validate what you need

does not loop and display the error message

Ok, I have this code that asks an input for a username and a password. I used JOptionPane. What I want with the program is to display an error message if the the input on the username field has a number, and goes back to the previous dialog box asking for the username again. I have this while loop yet it does not function the way it should. Please do help. The program does not show the error message on my catch method and neither does it loop for the dialog box to display.
public class SwingExercise {
public static void main(String[] args) {
String name = "";
String pw = "";
boolean input = true;
boolean hasDigit = false;
while (input) {
try {
while (name.equals("")) {
name = JOptionPane.showInputDialog(null, "Enter username:");
if (name.equals("")) {
JOptionPane.showMessageDialog(
null, "No input.", "Error", JOptionPane.ERROR_MESSAGE);
name = "";
}
while (hasDigit) {
for (int i = 0; i < name.length(); i++) {
if (Character.isDigit(name.charAt(i))) {
throw new InputMismatchException();
}
}
hasDigit = false;
}
}
input = false;
while (pw.equals("")) {
pw = JOptionPane.showInputDialog(null, "Enter password:");
if (pw.equals("")) {
JOptionPane.showMessageDialog(
null, "No input.", "Error", JOptionPane.ERROR_MESSAGE);
pw = "";
}
}
} catch (NullPointerException e) {
System.exit(0);
} catch (InputMismatchException e) {
JOptionPane.showMessageDialog(
null, "Invalid input.", "Error", JOptionPane.INFORMATION_MESSAGE);
}
}
}
Please do mention any comments regarding the other lines in my code and if there are any unnecessary lines. Thank you in advance :)
There seems to be absolutley no way to get into the while(hasDigit) loop because you have it set to false, and there is nothing setting it to true.
One problem is that the value of hasDigit will always remain false. You probably will want to define hasDigit as true initially.
boolean hasDigit = true;
Some comments on style, since you asked:
In general, you want your try() blocks to be as short as possible, so it's clear which lines you're expecting to throw an exception. Otherwise you may unexpectedly catch an exception from a line that you didn't think could generate it, and then handle it incorrectly. This means the code will probably be longer, but it's far more important that it be easier to maintain and debug.
When it's legitimate for a string to be null, it's common to write if ("".equals(name)) rather than if (name.equals("")). Since the hard-coded empty string can never be null, you needn't surround the code with a try/catch block.
There's no need to set name or pw to the empty string inside an if() that tests to see if they're empty.
You probably don't want to echo the password. See JOptionPane to get password.
The code explicitly forbids digits in the name but accepts every other character, including punctuation and special characters. It's generally good programming practice to use a whitelist of acceptable input, rather than a blacklist of forbidden input. That way you'll never be surprised by invalid data that's unexpectedly accepted.
The outermost while() loop will exit if the password is invalid, since input only depends on the name. Better to set input to false at the top of the loop, then set it to true if either input is invalid.
Since the name and pw blocks are almost identical (they prompt for a non-empty string), consider extracting them into a helper function. You'll want to pass parameters that specify the prompt and whether or not to echo the input back to the user.

Java Try and catch

I have a java program that is supposed to handle an Exception, but the end result is far from what I intended it to be. Here is the overall idea of my program: it is supposed accept an input of zero and exit the program. The input dialog should cause an Exception which should be caught and print the message "bad number".
My brain is telling me I'm missing one line of code in the catch block.
here is my code:
import javax.swing.JOptionPane;
public class exceptTest {
public static void main(String[] args){
try {
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0"));
System.exit(0);
}catch(Exception e){
JOptionPane.showMessageDialog(null, "bad number");
}
}
}
You are not catching an exception here, you are simply making a if statement, you can just use an if/else.
try{
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0")){
System.exit(0);
}else{
JOptionPane.showMessageDialog(null, "bad number");
}
}catch (Exception ex){
ex.printStackTrace();
}
The catch you would only use for any exceptions showInputDialog() throws, but for your number check you are not catching anything, it just simply is not 0.
You don't execute your exception handling code because you never throw an exception. The code will execute the input, then test the input to be equal to "0", then based on that will or will not display a dialog, and then it will execute.
The throwing of an exception occurs either because something has happened outside the conditions that the code will handle, or because you throw one explicitly.
By "outside the conditions" etc., I mean something like dividing by 0. Java (nor any other language) will handle that, and an exception will be thrown. The normal steps of procedural processing will stop, and an execution handler will be called.
In your case, if you (for instance) attempted to parse the input to be a number, but the input was not a number, you would get an exception. This is different functionality than you say you wanted, but is a better illustration of what an exception is for. Something like
try
{
int numberEntered = Integer.parse(line);
JOptionPane.showMessageDialog(null, "Entered a number, parsed to " + numberEntered);
}
catch (NumberFormatException nfe)
{
JOptionPane.showMessageDialog(null, "Did not enter a number, but <" + line + ">");
}
shows the sort of thing exceptions are normally good for.
If you wanted to, you could define an exception, call it BadNumberException, and throw it in the code you have -- you would put it (I guess) in an else clause for your if statement. But your routine would be throwing the exception, and I think it is unusual for the routine that throws an exception to also catch it.
Hope that helps.
rc
You have a semi-colon after your if statement, it terminates the line and the compiler does not look for the rest of the if. Remove your semi-colon and it will work fine.
import javax.swing.JOptionPane;
public class exceptTest
{
public static void main(String[] args){
try
{
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0")) //semi-colon removed here
{
System.exit(0);
}
throw new IllegalArgumentException("Input was not 0");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "bad number");
}
}
}
Your code does not throw an exception if the input is not equal to 0. Therefore, you never catch anything, thus no errormessage is shown on the screen.
You could do two things:
- throw an exception if the input is not 0 (then you will enter the catch)
or
- use an else with your if that displays the error message (then you don't need the try-catch for checking whether the input is 0)
Edit: And of course as Hunter McMillen noticed, you need to remove the semicolon after your if statement.

Categories

Resources