我正在创建一个系统,用于验证已在数据库中定义的凭据与在jTextfield中输入的凭据。当我在if-else语句中输入条件时,它表示不能将String转换为boolean。请帮忙。
Connection con = (Connection) DriverManager.getConnection (host, uName, uPass);
Statement stmt = (Statement) con.createStatement ();
//login is a table in my database,password a tuple
String SQL = "SELECT password FROM login;";
ResultSet password = stmt.executeQuery (SQL);
String pass = adminpassword.getText();
String sqlpass = password.getString("password");
//error shows on if else below
if(sqlpass = pass){
JOptionPane.showMessageDialog(null,"You have entered an incorrect password,please try again.","Incorrect Password",JOptionPane.WARNING_MESSAGE);
}
else{
String passconfirm = "SELECT admin_id WHERE password = 77353";
ResultSet confirmpass = stmt.executeQuery(passconfirm);
JOptionPane.showMessageDialog(null,"Welcome","Welcome " + confirmpass,JOptionPane.INFORMATION_MESSAGE);
Countyinfo proceed = new Countyinfo();
proceed.setVisible(true);
}
}
catch(SQLException err){
System.out.println (err.getMessage());
};
答案 0 :(得分:1)
相等性的布尔运算符是==
,而不是=
(它是赋值运算符)。赋值操作将始终计算为分配给其左值的值。
这就是sqlpass = pass
评估为String
的原因。
sqlpass == pass
将评估为boolean
。
编辑:
不过,比较String
的标准方法是使用.equals
方法,如下所示:
if(sqlpass.equals(pass))
答案 1 :(得分:1)
您的if
语句表达式中有一项作业,该作业返回String
而不是必需的boolean
。
if (sqlpass = pass) {
应该是
if (sqlpass.equals(pass)) {
比较Strings
(==
运算符比较Object
引用而非内容)