我正在尝试创建一个JFrame来检查放置在JTextField中的文本是否与.txt文件中的信息相同。 然后,如果这是正确的,它会检查JPasswordField中的信息是否与.txt文件中的信息匹配。
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == button)
{
if(!username.getText().equals("") && passIsGood())
{
try
{
Scanner reader = new Scanner(new File("users.txt"));
reader.useDelimiter("\t|\n");
reader.nextLine();
while(reader.hasNextLine())
{
if(reader.next().equals(username.getText()))
{
//Username is correct, now checks for password:
System.out.println("Username passed");
if(reader.next().equals(passToString()))
{
//Username & Password are correct
System.out.println("Password passed");
break;
}
} else if(!reader.hasNextLine())
{
wrongInfo();
} else
{
reader.nextLine();
}
}
reader.close();
frame.dispose();
} catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex);
}
} else
{
JOptionPane.showMessageDialog(null, "Please enter a valid Username and Password");
}
}
}
private static String passToString()
{
String passString = new String(password.getPassword());
return passString;
}
我得到了用户名传递,但我觉得.equals(passToString())可能会导致问题。 文本文件如下所示: 用户名密码 测试测试 test2 thetest3
请注意,每个字段之间的空格是制表符,因此我的分隔符使用(“\ t | \ n”);
答案 0 :(得分:1)
文本字段中包含的字符串可能包含一些不需要的字符。使用字符域(作为符号的所有ascii值)来摆脱它们。试试这个:
import java.io.File;
import java.util.Scanner;
public class readUsers {
public static void main(String[] args) {
try {
Scanner reader = new Scanner(new File("users.txt"));
reader.useDelimiter("\t|\n");
String username = "username";
String password = "password";
for (int i = 0; i < username.length(); i++) {
//replace possible unwanted characters
if (username.charAt(i) < 33 || username.charAt(i) > 126)
username = username.replace(Character.toString(username.charAt(i)), "");
}
for (int j = 0; j < password.length(); j++) {
//replace possible unwanted characters
if (password.charAt(j) < 33 || password.charAt(j) > 126)
password = password.replace(Character.toString(password.charAt(j)), "");
}
while (reader.hasNextLine()) {
String user = reader.next();
String pass = reader.next();
//if username equals the user in the textfile, check if password equals the pass in the file
if (user.equals(username)) {
System.out.println("username passed!");
if (pass.equals(password))
System.out.println("password passed!");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
我的文本文件如下所示:
用户名密码
username2密码
P.S。这是我的第一个StackOverFlow答案,如果我做错了,请纠正我:)