Reputation: 31
So i should read ID,UserName,Password from a textfile (They are seprated by "~!~") 1~!~Jhon~!~12345 2~!~Mark~!~12345 3~!~Linda~!~abcde 4~!~Mary~!~qwerty here is how the text file looks like, my code always prompts false even when my input is (1 Jhon 12345).
public boolean LoginAsAdmin (int myID,String myUserName,String myPassword) throws 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;
}
Upvotes: 0
Views: 31
Reputation: 44844
You do not want to put nextToken
with an if
statement, as it will fail early if the first test
is false
- Also I not not sure why your setters
are returning boolean values.
Firstly I suggest that you use a BufferedReader to read you lines from a text file - see https://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/ for an example.
Then for each line do
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);
}
Upvotes: 1