文件io搜索,直到匹配java
所以我有accounts.txt文件,其中包括文件io搜索,直到匹配java,java,loops,netbeans,file-io,Java,Loops,Netbeans,File Io,所以我有accounts.txt文件,其中包括 abcd 1234 efgh 5678 这是我的搜索代码 扫描仪扫描=空 try { scan = new Scanner(new File("accounts.txt")); } catch (Exception e) { e.printStackTrace(); } String inpUser; inpUser = usernameTextField.getTex
abcd
1234
efgh
5678
这是我的搜索代码
扫描仪扫描=空
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");
}
如果我运行程序并尝试输入efgh
和5678
,它会说错误的密码/用户名,因为它只检查accounts.txt
中的前两行。如何更改代码,使其检查整个文件而不仅仅是前两行
--新问题--
我已经这样做了:
String user="";
String pass="";
while(scan.hasNextLine()){
user = scan.nextLine();
pass = scan.nextLine();
}
但是现在它跳过accounts.txt中的前两行,从第3行开始。确保使用while循环读取文件中的所有输入。 看看你的代码:
String user="";
if(scan.hasNextLine()) // if statement performs operation only once
user = scan.nextLine(); // this is the operation to perform once
String pass="";
if(scan.hasNextLine()) // if statement performs operation only once
pass = scan.nextLine(); // this is the operation to perform once
这句话你只读了一次。
尝试使用while循环(多次迭代)而不是if语句(一次)首先,您的代码只检查了前两行。如果试图进行身份验证的用户不在文件的顶部,则会出现问题。第二,您尝试了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");
使用while循环读取所有行,而不是if条件。@Omore这很好用。谢谢如果我回答了你的问题,请在我发现错误时将我的回答标记为正确。我有
String user=”“;字符串pass=“”;而(scan.hasNextLine()){user=scan.nextLine();pass=scan.nextLine();}
则跳过前两行。为什么?请用你的新问题编辑你原来的帖子。一旦你这样做了,在这里评论你已经这样做了,我会编辑我的原始答案来帮助你。但请在编辑中发布所有代码,否则我帮不上忙。