[英]How to break the while loop in this java program
我正在使用 java 進行登錄。 身份驗證繼續循環並顯示錯誤消息,直到它獲得正確的用戶名和密碼。 如何解決? 我只希望它在找到時破壞,並且僅在未找到時顯示未找到。
private void loginbtnActionPerformed(java.awt.event.ActionEvent evt) {
String username = usertxt.getText();
String password = passwordtxt.getText();
try
{
File login = new File("logindata.txt");
Scanner scan = new Scanner(login);
scan.useDelimiter("[,\n]");
while(scan.hasNext())
{
String user = scan.next();
String pass = scan.next();
if (username.equals(user.trim()) && password.equals(pass.trim()))
{
JOptionPane.showMessageDialog(null,"Welcome!"+username);
this.dispose();
new peopleoptions().setVisible(true);
break;
}
else
{
JOptionPane.showMessageDialog(null,"User not found, please register");
}
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"System Error");
}
}
我的評論作為代碼,幾乎沒有重新思考:
...
scan.useDelimiter("[,\n]");
boolean found = false; // Memorize...
while (!found && scan.hasNext()) { // ...process until found or end ("until(x or y)" <=> "while not(x and y)";)
String user = scan.next();
String pass = scan.next();
if (username.equals(user.trim()) && password.equals(pass.trim())) {
found = true; // .. don't break...
}
}
// show dialog (and do "the action") only after "processing database" ...
if (found) {
// log.info("yay");
JOptionPane.showMessageDialog(null,"Welcome!"+username);
new peopleoptions().setVisible(true);
} else { // ... AND not found!;)
JOptionPane.showMessageDialog(null,"Credentials invalid, please register new user or reset password");
}
// really??: this.dispose(); // in any case?? maybe: "finally"!
} catch( ...
面對眼前的問題,它歸結為:
請“釋放”您的資源(文件、掃描儀……)!!
java >= 8:
分別測試用戶和密碼:
while (scan.hasNext()) {
String user = scan.next();
String pass = scan.next();
if (username.equals(user.trim())) {
if (password.equals(pass.trim())) {
JOptionPane.showMessageDialog(null, "Welcome!"+username);
dispose();
new peopleoptions().setVisible(true);
break;
} else {
JOptionPane.showMessageDialog(null, "Password incorrect. Please try again");
}
} else {
JOptionPane.showMessageDialog(null, "User not found, please register");
}
}
不要在 if 中使用 break 命令,而應該在 While 中使用它。 或者你可以試試 if condition scan.hasNext() = false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.