krushio vida krushio vida - 3 months ago 13
Java Question

validate input using try catch

I am trying to validate input text field in java by creating an exceptional error if user does not type in the word specified i.e. admin

String username;
int phone1;

@Override
public void widgetSelected(SelectionEvent e) {
try
{
phone1 = Integer.parseInt(phone.getText());
}
catch (Exception exe)
{
MessageDialog.openError(shell, "Error","Phone number has to be a number");
return;
}

try
{
username = namefield.getText();
if (username!= "admin") {
throw (new Exception());
}
}
catch (Exception exe)
{
MessageDialog.openError(shell, "Error","The username must be admin");
return;
}


labelresult.setText("The name entered is:"+ username );


labelresult2.setText("The phone entered is:"+ phone1 );


The one for phone works perfectly

What about for username. What should i do?

Answer

As @simonv mentioned in comment, Don't use exception to control program flow. But if you are learning try-catch, than you can try this. Also improve your if statement. You are comparing string object. So use equals() method as following:

        try
        {
        username = namefield.getText();
           if (!"admin".equals(username)) {
                throw new Exception("YOUR_MESSAGE_HERE");
            }           
        }
        catch (Exception exe)
        {   
            System.out.println(exe);
            return;
        }
Comments