I am writing a login code for a project I'm working on that includes CSV files. the code works fine if I put a constant value to File for example File = ("admins.csv"), but when I try to change the file depending on the input the program executes incorrectly.
The output comes out like this:
0-login as an Admin
1-login as a Librarian
0 Enter username: Enter password: admin false
login class:
import java.util.ArrayList;
import java.util.Scanner;
public class Login {
public static Scanner sc = new Scanner(System.in);
private static ArrayList<User> users;
public static String File;
public static synchronized void readUsers(int x){
switch (x) {
case 0:
File = ("admins.csv");
break;
case 1:
File = ("libs.csv");
break;
default:
File = ("admins.csv");
}
if(null == users){
users = new ArrayList<User>();
Scanner scan = new Scanner (Login.class.getResourceAsStream(File));
String line;
while((scan.hasNextLine())){
line=scan.nextLine();
String[] tokens = line.split(",");
users.add(new User(Integer.parseInt(tokens[0]), tokens[1], tokens[2]));
}
}
}
public static synchronized boolean find( String username, String password){
if(null == users){
throw new IllegalStateException("user list is not initialised");
}
return users.stream()
.filter(u -> u.getUsername().equals(username))
.filter(u -> u.getPassword().equals(password))
.findFirst()
.isPresent();
}
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
System.out.println("0-login as an Admin");
System.out.println("1-login as an Librarian");
int x= sc.nextInt();
readUsers(x);
System.out.println("Enter username:");
String name = sc.nextLine();
System.out.println("Enter password:");
String pass = sc.nextLine();
if( find(name, pass)==true) {
System.out.println("true");
} else;
System.out.println("false");
}
}}
User class:
class User{
private int id;
private String username;
private String password;
public User(int id, String username, String password){
this.id = id;
this.username = username;
this.password = password;
}
public int getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}