gpt4 book ai didi

java - 文件 io 搜索直到匹配 java

转载 作者:行者123 更新时间:2023-11-30 02:34:28 25 4
gpt4 key购买 nike

所以我有accounts.txt 文件,其中包括

abcd
1234
efgh
5678

这是我的搜索代码

扫描仪scan=null;

    try {
scan = new Scanner(new File("accounts.txt"));

} catch (Exception e) {

e.printStackTrace();
}

String inpUser;
inpUser = usernameTextField.getText();

String inpPass;
inpPass = pinNumberTextField.getText();

String user="";
if(scan.hasNextLine())
user = scan.nextLine();

String pass="";
if(scan.hasNextLine())
pass = scan.nextLine();

if (inpUser.equals(user)&& inpPass.equals(pass)){
accountGUI s = new accountGUI();
s.setVisible(true);
}else {
JOptionPane.showMessageDialog(null,"Wrong Password / Username");
}

如果我运行程序并尝试输入 efgh5678 ,它会显示错误的密码/用户名,因为它只检查 accounts 中的前两行。 txt.如何更改代码以便它检查整个文件而不仅仅是前两行?

-- 新问题--我已经这样做了:

String user="";
String pass="";

while(scan.hasNextLine()){
user = scan.nextLine();
pass = scan.nextLine();
}

但现在它会跳过accounts.txt中的前两行并从第3行开始。

最佳答案

首先,您的代码仅检查前两行。如果尝试进行身份验证的用户不在文件顶部,则会出现问题。其次,您尝试了 while 循环,但是 while 循环会遍历文件中的每一行,直到到达末尾,并且除了最后两行之外不会检查任何内容。

while 循环接近正确,但您需要在每一对行中添加一个检查,如果这是用户输入的对,则您可以成功验证它们。然后,我们只跟踪是否找到用户 - 如果我们到达文件末尾而没有找到正确的用户,我们会显示错误消息。

String user="";
String pass="";

boolean foundUser = false; // Keeps track of if we found the user's credentials

while(scan.hasNextLine()) {
// get username (we know it is there)
user = scan.nextLine();

// Get password, making sure to check it exists!
if(scan.hasNextLine())
pass = scan.nextLine();

// If we have found the user's credentials, log in
if (inpUser.equals(user) && inpPass.equals(pass)) {
accountGUI s = new accountGUI();
s.setVisible(true);
foundUser = true;
break; // We found the user, stop looping (stop looking)
}
}

// If we've reached the end of the file, and not found the user
if(!foundUser)
JOptionPane.showMessageDialog(null,"Wrong Password / Username");

关于java - 文件 io 搜索直到匹配 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43458077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com