我正在嘗試將用戶輸入名稱與檔案 javaFx 中的現有名稱進行比較,如果它相同的名稱會收到警報,如果不會出現另一個視窗。但即使名稱存在,我也總是得到新視窗有什么建議嗎?
void submitBu(ActionEvent event) throws FileNotFoundException {
File file=new File("/Users/AL/info.txt");
String name=nameTextField.getText();
Scanner n =new Scanner(file);
//show alert if info already exists in file
while(n.hasNextLine()) {
String s=n.nextLine();
if(s.equalsIgnoreCase(name)) {
displayMessage("Unsuccessfull login. Try again.", AlertType.ERROR);
break;
}
Pane root;
try {
root = FXMLLoader.load(getClass().getResource("/view/CreditCard.fxml"));
Stage stage=new Stage();
stage.setScene(new Scene(root, 600, 400));
stage.setTitle("CrediCard");
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
uj5u.com熱心網友回復:
如果 info.txt 檔案中已經存在警報,您希望顯示警報。否則,您要打開另一個視窗。您的方法的撰寫方式并沒有這樣做。您的代碼中有太多邏輯缺陷。
這是您使用過的 while 回圈。我添加了注釋以使每個任務更清晰易懂。
// if there are more names in the file
while(n.hasNextLine())
{
// retrieve a name
String s = n.nextLine();
// check is the inputted name matches with the retrieved name
if(s.equalsIgnoreCase(name))
{
// if it does, show error dialog and exit
displayMessage("Unsuccessfull login. Try again.", AlertType.ERROR);
break;
}
// if it does not, create a new window
Pane root;
try
{
root = FXMLLoader.load(getClass().getResource("/view/CreditCard.fxml"));
Stage stage=new Stage();
stage.setScene(new Scene(root, 600, 400));
stage.setTitle("CrediCard");
stage.show();
}
catch (IOException e) { e.printStackTrace(); }
// exit after one iteration
break;
}
最后一個 break 陳述句是問題所在。這里發生的事情是,您檢查檔案中的第一個名稱是否與輸入名稱匹配。如果是,顯示警報,否則顯示新視窗。您的方法不會使用輸入名稱檢查檔案中的任何其他名稱。很容易弄清楚為什么會發生這種情況。
如果您想根據輸入名稱檢查檔案中的所有名稱,然后,如果沒有名稱與輸入名稱匹配,則執行您所說的操作。這是有效的方法。
void submitButton(ActionEvent actionEvent)
{
File infoFile = new File("path/to/file");
Scanner scanner = new Scanner(System.in);
String inputName = nameTextField.getText();
while (scanner.hasNextLine())
{
String fileName = scanner.nextLine();
if (inputName.equalsIgnoreCase(fileName))
{
// show alert
return;
}
}
// you will only reach here if none of the file name matches the input name
// show new window
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/341719.html
上一篇:掃雷程式超過時限
下一篇:將C專案轉換為庫以在QT中使用
