SOLVED!
I have a kind of homework, where I have a file where I have username and password like this:
user1 password1
user2 password2
user3 password3
I need to use FileInputStream class, and I also need to keyboard input username and password and check if it already exists (every username must match password, on line). I decided to use Map for that but .... if you take a look into my while loop, I tried to split into key and value. I also created map2 who stores keyboard input, and map who stores split key and value.
My trouble is here: if I input username: user1, password: password1, that condition if(map.equals(map2)) will return true. But if I write for username: user2 and password: password2, "if" will return false, even if user2 and password2 already exists in my file.
Tip: I can't override equals() and hashCode() because I don't have any class here, out of my main class.
public class ex_2
{
public static void main(String args[]) throws IOException
{
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(reader);
System.out.print("username: ");
String user = br.readLine();
System.out.print("password : ");
String pass = br.readLine();
FileInputStream input= new FileInputStream("file.txt");
BufferedReader read= new BufferedReader(new InputStreamReader(input));
Map<String, String> map = new HashMap<String,String>();
Map<String, String> map2 = new HashMap<String,String>();
map2.put(user, pass);
System.out.println(map2);
String line;
while((line = read.readLine()) !=null)
{
String[] split = line.split("\t\t");
map.put(split[0], split[1]);
if(map.equals(map2))
{
System.out.println("True");
}
else
{
System.out.println("False");
}
}
System.out.println(map);
read.close();
code for @SMA
String line;
while((line = read.readLine()) !=null)
{
String[] split = line.split("\t\t");
map.put(split[0], split[1]);
String passwordInFile = map.get(user);
if (passwordInFile != null && passwordInFile.equals(pass))
System.out.println("True");
else
System.out.println("False");
}
You shouldn't be comparing two maps. Instead compare for values in the map once you have all the values that are stored in a file like:
String passwordInFile = map.get(user)
if (passwordInFile != null && passwordInFile.equals(pass)) {
System.out.println("True");
} else {
System.out.println("False");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.