【发布时间】:2015-05-12 04:14:34
【问题描述】:
我认为 user.contains 并没有读取每一行,而只是检查第一行。我之前有这个工作正常(我正在测试我的代码的重复用户部分),但现在我的程序正在跳过:
{
JOptionPane.showMessageDialog(null, "Duplicate user found.");
goahead=false;
dispose();
}
我不确定我做了什么,或者我是如何设法破坏自己的程序的。现在它一直跳到:
else { if (hs.contains(new String(un+" "+pw))) {
JOptionPane.showMessageDialog(null,"User, Found Access Granted!");
dispose();
}
我哪里做错了?
private void SubmitActionPerformed(java.awt.event.ActionEvent evt) {
String un = UserName.getText().trim();
String pw = Password.getText().trim();
HashSet hs= new HashSet();
HashSet users = new HashSet();
boolean goahead=true;
try {
Scanner Scan = new Scanner(new File("Login.txt"));
while (Scan.hasNextLine()) {
String authenticator = Scan.nextLine().trim();
String[] autparts=authenticator.split(" ");
String user = autparts[0].trim();
if (goahead){
if (users.contains(user)) {
if (user.equals(un)) {
JOptionPane.showMessageDialog(null, "Duplicate user found.");
goahead=false;
dispose();
}
} else {
hs.add(authenticator);
users.add(user);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
if (goahead) {
if (createAccount.isSelected() & (hs.contains(new String(un+" "+pw)))){
JOptionPane.showMessageDialog(null,"User Already Exsist! No Need to create a new account. ");
dispose();
} else {
if (hs.contains(new String(un+" "+pw))) {
JOptionPane.showMessageDialog(null,"User, Found Access Granted!");
dispose();
} else {
if (createAccount.isSelected()){
try {
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("Login.txt", true)));
output.println(un+" "+pw);
output.close();
} catch (IOException ex) {
System.out.printf("error %s/n", ex );
}
JOptionPane.showMessageDialog(null,"Welcome!"+" " + un+" "+"Please Relogin Now");
dispose();
}else {
JOptionPane.showMessageDialog(null, "user doesn't exist or password incorrect. ");
dispose();
}
}
}
}
以下是我的输出和 txt 文件中的内容。 :
【问题讨论】:
-
请正确格式化代码。
-
users在您发布的调试器窗口中的大小为0。 -
if (goahead) {始终是true,所以if (users.contains(user)) {实际上从未被评估... -
谢谢,这些答案确实有道理。我不知道如何解决它。 (我是新人)
-
你在追逐你的尾巴,你试图加载文件并填充
usersSet同时试图确定用户提供的值是否在列表中...... ??填充Set然后检查输入是否存在或通过读取文件检查用户是否存在...
标签: java authentication java.util.scanner logical-operators login-control