所以我应该从文本文件中读取ID,UserName,Password(用“〜!〜”分隔)1〜!〜Jhon〜!〜12345 2〜!〜马克〜!〜12345 3〜!〜琳达〜!〜abcde 4〜!〜玛丽〜!〜qwerty 这是文本文件的外观,即使我输入的是(1 Jhon 12345),我的代码也总是提示false。
布尔布尔值LoginAsAdmin(整数myID,字符串myUserName,字符串myPassword)抛出FileNotFoundException {
File myFile = new File ("D:\\Java\\DATA.txt");
Scanner Writer = new Scanner(myFile);
int j = 0;
while (Writer.hasNext()){
Admin myAdmin1 = new Admin();
String output = Writer.nextLine();
StringTokenizer Data = new StringTokenizer(output,"~!~");
if(
myAdmin1.setID(Integer.parseInt((String) Data.nextToken()))&&
myAdmin1.setUserName((String) Data.nextToken())&&
myAdmin1.setPassword((String) Data.nextToken())){
myAdmin[j] = myAdmin1;
}
j++;
}
for (int i = 0; i < j; i++){
if(myAdmin[i].getID() == myID && myAdmin[i].getUserName().equals(myUserName) && myAdmin[i].getPassword().equals(myPassword)){
return true;
}
}
return false;
}
答案 0 :(得分:1)
您不希望在nextToken
后面加上if
语句,因为如果第一个test
是false
,它会很早就失败-同样,我不确定您为什么setters
返回布尔值。
首先,我建议您使用BufferedReader读取文本文件中的行-有关示例,请参见https://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/。
然后为每一行做
String arr[] = inputStr.split("~!~");
for (int i = 0; i < arr.length; i = i + 3) {
Admin myAdmin1 = new Admin ();
String id = arr[i];
myAdmin1.setId (id);
String name = arr[i + 1];
myAdmin1.setUsername (name);
String passwd = arr[i + 2];
myAdmin1.setPassword (passwd)
myAdmin[i % 3] = myAdmin1;
System.out.printf("%d %s %s%n", Integer.parseInt(id), name, passwd);
}