如何在if
语句中使用组合框中的选定项(组合框值转换为string
),java编译器显示不兼容的类型错误,说string
无法转换为Boolean
。请帮忙:)提前谢谢你。
代码:
private void btnSignInActionPerformed(java.awt.event.ActionEvent evt) {
String userid = txtUserID.getText();
String username = txtUserName.getText();
String usertype = cmboUserType.getSelectedItem().toString();
DBConnector dbcon = new DBConnector();
dbcon.connect();
if(dbcon.isUserExists(userid, username,usertype)){
if (usertype = "Customer"){
msg.showMessageDialog(
this,
"Login Successful",
"Login Status",
1);
OrganicFoods.Customer cust = new OrganicFoods.Customer();
cust.setVisible(true);
}
else if ( usertype = "StoreAdmin"){
msg.showMessageDialog(
this,
"Login Successful",
"Login Status",
1);
OrganicFoods.StoreAdmin S1 = new OrganicFoods.StoreAdmin();
S1.setVisible(true);
}
else if ( usertype = "Collection_Delivery_Officer"){
msg.showMessageDialog(
this,
"Login Successful",
"Login Status",
1);
OrganicFoods.Collection_Delivery_Officer cdo1 = new OrganicFoods.Collection_Delivery_Officer();
cdo1.setVisible(true);
}
}else{
msg.showMessageDialog(
this,
"Login Failure",
"Login Status",
0);
}
}
答案 0 :(得分:1)
==
比较对象引用
.equals()
比较字符串值
此外,要检查if
/ else if
语句中的条件,您必须使用==
符号,而不是=
,因为=
运算符将将值赋给String,而不是根据需要进行比较。
使用Strings
符号比较==
不是检查比较对象而不是值的最佳方法。
因此,对于特定程序,您必须使用如下所示的代码段:
if (usertype.equals("Customer")) {
//your algorithm
}