【发布时间】:2018-06-10 18:55:49
【问题描述】:
我正在为一个类分配创建一个登录页面,并且在一个方法接收用户名和密码然后在多行文本文件中搜索匹配项后退出 while 循环时遇到问题。它可以找到匹配项,但会返回主方法中的输入区域并再次询问用户名。希望这是有道理的。
任何帮助将不胜感激。如您所知,我是 Java 新手,因为这段代码到处都是,而且可能有很多错误。我整晚都在想办法解决这个问题,但没有运气。谢谢!
package course.registration;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Welcome {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Course Registration System" + "\n");
System.out.print("Please type Login or Register: ");
String choice = input.nextLine();
while (choice.equalsIgnoreCase("Login")){
System.out.print("Please enter email address to log in: ");
String email = input.nextLine();
System.out.print("Please enter password: ");
String password = input.nextLine();
//goes to method to search and match inputs
VerifyLogin verify = new VerifyLogin();
verify.VerifyInfo(email, password);
}
if (choice.equalsIgnoreCase("Register")) {
System.out.println("Going to registration Page...");
}
input.close();
}
}
这是搜索文本文件并尝试为输入找到匹配项的方法。我觉得问题出在方法退出并返回到 main 方法中的 while 循环时。我想不出退出while循环的方法。以下是字符串在“students_logins.txt”文件中的样子:
jthomas@gmail.com,1234
kwatson@time.com,3333
legal@prog.com,d567
lavern@shirley.com,34
kwatson@gmail.com,12200
package course.registration;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class VerifyLogin {
private String tempUsername;
private String tempPassword;
public void VerifyInfo(String email, String password) throws FileNotFoundException {
boolean login = false;
File file = new File("student_logins.txt");
Scanner info = new Scanner(file);
info.useDelimiter("[,\n]");
while (info.hasNextLine()) {
tempUsername = info.next();
tempPassword = info.next();
if (tempUsername.trim().equals(email.trim()) && (tempPassword.trim().equals(password.trim()))) {
System.out.println("Email Address or Password Works!!");
break;
}
}
if (!login) {
System.out.println("Email Address or Password is Invalid.");
}
info.close();
}
}
【问题讨论】:
标签: java while-loop java.util.scanner user-input