Home > Mobile >  I'm trying to make an (if , else) statement but it does not work
I'm trying to make an (if , else) statement but it does not work

Time:05-19

I'm making a small program that needs a login I'm using SQLite as a database and working with NetBeans ide the first (if, else statement) here is to ensure that the user does not leave the text field or the password field empty and it does not work the second (if, else statement) is to check if the password and username are in the database and its working fine here is my code::

private void btnloginActionPerformed(java.awt.event.ActionEvent evt) {                                         
  
if(jTextField1.getText()== "" || jPasswordField1.getText()=="")
{JOptionPane.showMessageDialog(this, "the usernmae or bassword filed is empty");}

else {
     String sql = "SELECT * from Accounts WHERE User LIKE ? AND pass LIKE ? ; ";
    try{
        pst = con.prepareStatement(sql);
        pst.setString(1, jTextField1.getText());
        pst.setString(2, jPasswordField1.getText());
        rs = pst.executeQuery();
                
        if (rs.next()){
            
            JOptionPane.showMessageDialog(null,"log in successful");
            
            java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new booking().setVisible(true);
                dispose();
            }
        });
                    
                      }
        else 
        {
            JOptionPane.showMessageDialog(this, " wrong username or password ");
            
        }
    }
    catch (Exception e){
        
            JOptionPane.showMessageDialog(this, "error " e);
    
    }} ```

CodePudding user response:

These conditions are invalid. You need to use the equal method in the String

jTextField1.getText().equal("") || jPasswordField1.getText().equal("")

Or you can use

jTextField1.getText().isEmpty() || jPasswordField1.getText().isEmpty()

More info here:

https://www.geeksforgeeks.org/difference-between-and-equals-method-in-java/#:~:text=We can use == operators,of values in the objects.

CodePudding user response:

Best approach first save those username and password in string object.

String username=jTextField1.getText();
String password=jPasswordField1.getText();

Now compare them with null and length.

if((username!=null && username.length>0) || (password!=null && password.length>0)){
//write sql query
}else{
//error message
} 
  • Related