【发布时间】:2017-04-11 09:56:27
【问题描述】:
我的java类。它具有所有必要的软件包。我正在使用命令行界面。
public static boolean checkLibIDPass(){
boolean continueLogin = true;
boolean check = false;
boolean retry = false;
while (continueLogin){
Scanner Sc = new Scanner(System.in);
String _id,_pass;
int goBack;
System.out.println("Input Librarian ID: ");
_id = Sc.next();
System.out.println("Input Librarian Password: ");
_pass = Sc.next();
try {
BufferedReader br = new BufferedReader(new FileReader("LibrarianFile.txt"));
String line = null;
while ((line = br.readLine()) != null && retry == false) {
String[] values = line.split("\t",-1);
for (int i=0; i < values.length; i++) {
if((_id.equals(values[0])) && (_pass.equals(values[1]))){
check = true;
retry = true;
System.out.println("Login Successful!");
break;
}
else if(i == values.length -1){
System.out.println("Librarian ID or Password is invalid");
System.out.println("Retry Login?" + "\n" + "1 : Yes"+ "\n" + "2 : Choose another user");
goBack = Sc.nextInt();
if (goBack == 1){
retry = true;
continueLogin = true;
break;
}
else if (goBack == 2){
retry = true;
continueLogin = false;
break;
}
}
}
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
return check;
}
我的输出:
Welcome to Knowledgica's Library Management System !
Which type of user are you?
1 : Guest
2 : Librarian
3 : Admin
4 : Exit
2
Input Librarian ID:
aasdasd
Input Librarian Password:
asdasdasd
Librarian ID or Password is invalid
Retry Login?
1 : Yes
2 : Choose another user
1
Input Librarian ID:
asdasd
Input Librarian Password:
asdasd
Input Librarian ID:
sdasd
Input Librarian Password:
asdasdas
Input Librarian ID:
如果我想重试输入另一个 ID 和密码,我的目标是再次访问 try 子句。但是,它总是在没有 try 子句的情况下循环。
【问题讨论】:
-
你关闭过
BufferedReader吗?我不这么认为。要么在循环内关闭它,要么将该行从循环中取出,以便您打开文件一次,然后在循环内重新使用阅读器。然后在循环后关闭它。看看有没有帮助。 -
我假设您的意思是如果登录无效,您要重新读取文件。好吧,您的代码不会发生这种情况,因为 while 循环在 try 内,而读取的文件在 while 之外。您可以有一个“已验证”布尔值并在一段时间内包装读取的文件(bool = false),然后如果凭据有效,则在当前循环中将 bool 设置为 true
标签: java while-loop try-catch