问题描述
firstname lastname username password
John Doe $1234567 $123
Eden Hask $1234576 $12345
最近的登录(伊甸园)总是有效,但前一个(约翰)无效。 出于某种原因,分隔符将包含下一个 $ 之前的所有详细信息。 我应该如何让我的分隔符在密码之后停止。
The user name is_1234567 and the password is_123
Eden Hask!
The user name is_1234576 and the password is_12345!
这是完整的代码。
public void login() throws FileNotFoundException{
File file = new File("file.txt");
Scanner read = new Scanner(file);
found = false;
read.useDelimiter("(\s*\\$)");
try {
Scanner keyboard = new Scanner(system.in);
System.out.print("Username: ");
String username = keyboard.nextLine();
System.out.print("Password: ");
String passwordField = keyboard.nextLine();
while(read.hasNext()){
String user = read.next();
String pass = read.next();
System.out.println("The user name is_" + user + " and the password is_" + pass + "!\n");
if(user.trim().equals(username) && pass.trim().equals(passwordField)){
boolean found = true;
break;
}
}
if(found){
return true;
}
else {
return false;
}
read.close();
}catch(Exception e){
throw e;
}
};
解决方法
根据您的描述,您似乎也想在一行结束时断开字符串。为此,请按以下方式添加回车作为分隔情况之一-
read.useDelimiter("\n|(\s*\\$)")
这应该可以防止所有以前的“密码”字符串包含下一行的详细信息
,我会完全不同:
boolean found;
public void login() throws FileNotFoundException {
File file = new File("file.txt");
Scanner read = new Scanner(file);
try {
Scanner keyboard = new Scanner(System.in);
System.out.print("Username: ");
String username = keyboard.nextLine();
System.out.print("Password: ");
String password = keyboard.nextLine();
// Skip the first line
read.nextLine();
while (read.hasNextLine()) {
String line = read.nextLine();
//split current line with spaces into an array
String[] lineArray = line.split("\\s+");
String user = lineArray[1];
String pass = lineArray[4];
System.out.println("The user name is " + user + " and the password is " + pass + "!\n");
if (user.equals(username) && pass.equals(password)) {
found = true;
break;
}
}
read.close();
keyboard.close();
} catch (Exception e) {
e.printStackTrace();
}
}
,
除了分隔符中包含的换行符之外,您可能还想读取用户名以保持用户 ID/密码读取同步:
read.useDelimiter("(\\s*\\$)|(\\R)");
try {
Scanner keyboard = new Scanner(System.in);
System.out.print("Username: ");
String username = keyboard.nextLine();
System.out.print("Password: ");
String passwordField = keyboard.nextLine();
while(read.hasNext()){
String name = read.next();
String user = read.next();
String pass = read.next();