【发布时间】:2015-11-21 12:16:16
【问题描述】:
解决了!
我有一个作业,我有一个文件,其中有这样的用户名和密码:
用户1密码1
用户2密码2
用户3密码3
我需要使用 FileInputStream 类,我还需要键盘输入用户名和密码并检查它是否已经存在(每个用户名必须匹配密码,在线)。我决定为此使用 Map 但是....如果您查看我的 while 循环,我尝试将其拆分为键和值。我还创建了存储键盘输入的 map2 和存储拆分键和值的 map。
我的麻烦就在这里:如果我输入用户名:user1,密码:password1,则条件 if(map.equals(map2)) 将返回 true。但是如果我写用户名:user2 和密码:password2,“if”将返回 false,即使我的文件中已经存在 user2 和 password2。
提示:我不能覆盖 equals() 和 hashCode(),因为我这里没有任何类,在我的主类之外。
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();
@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");
}
【问题讨论】:
标签: java file dictionary hashmap