我正在做登录GUI。我遇到的问题是当程序从我的记事本读取用户名和密码时,它会弹出保存在txt文件中的每一行的消息。例如,我的txt文件中有三组用户名和密码,当程序读取txt文件的第一行时,如果输入的第一组用户名和密码匹配,则会弹出“登录成功”,但如果输入第二组密码和用户名,则会弹出“密码和用户名错误”,按确定后,则弹出“登录成功”。伙计们,我需要你们的帮助。谢谢
公共(public)无效actionPerformed(ActionEvent e){
String inputUser = input1.getText();
String inputPass = input2.getText();
File loginf = new File("oop.txt");
try{
Scanner read = new Scanner(new File("oop.txt"));
while(read.hasNext()){
String user = read.next();
String pass = read.next();
read.next();
if(inputUser.equals(user) && inputPass.equals(pass)){
JOptionPane.showMessageDialog(this, "Login Sucessful");
break;
}
else if(!inputUser.equals(user)&&!inputPass.equals(pass)){
JOptionPane.showMessageDialog(null,"Incorrect Username and Password");
}
}
read.close();
}
catch (FileNotFoundException qwerty){
JOptionPane.showMessageDialog(null, "Can't find a text file");
}
最佳答案
读取文件直到找到匹配项,设置标志或存储所需的值并跳出循环,然后决定显示哪条消息
boolean youShallNotPass = true;
while(read.hasNext()){
String user = read.next();
String pass = read.next();
read.next();
if(inputUser.equals(user) && inputPass.equals(pass)){
youShallNotPass = false;
break;
}
}
if(!youShallNotPass){
JOptionPane.showMessageDialog(this, "Login Sucessful");
} else {
JOptionPane.showMessageDialog(null,"Incorrect Username and Password");
}
关于java - 如何阻止程序读取每一行并弹出每一行的消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27351728/