2

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?

Omari Victor Omosa
  • 2,814
  • 2
  • 24
  • 46

2 Answers2

2

You should use:

 if(!username.equals("admin")){
 //your code
 }

To compare string you will have to use equals() method.

As suggested by simon, it is recommended to use:

if(!"admin".equals(username)){
 // your code 
}

In that way it will be null safe.

simonv
  • 99
  • 1
  • 2
  • 6
Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
2

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;
        }
Kaushal28
  • 5,377
  • 5
  • 41
  • 72