【问题标题】:Java, compare keyboard input values with file.txt valuesJava,将键盘输入值与 file.txt 值进行比较
【发布时间】: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


    【解决方案1】:

    您不应该比较两张地图。而是在将所有值存储在文件中后比较地图中的值,例如:

     String passwordInFile = map.get(user)
     if (passwordInFile != null && passwordInFile.equals(pass)) {
         System.out.println("True");
     } else {
         System.out.println("False");
     }
    

    【讨论】:

    • 感谢您的回复。但它不起作用......现在如果我输入与 .txt 文件中相同的值,我会得到错误
    • @ClaudiuM 你不觉得在你的代码中使用 line 是有意义的吗? (我说的是你编辑的代码sn-p)
    • 哦,你是对的@Tom!我忘记粘贴那个代码序列了。
    • 现在好像可以了。但是我在while循环中仍然有一个问题,例如,它打印假,假,真。如果我在 if 中使用 break 并在 else ofc 中使用另一个 break,使用 { },我认为每个条件都为 false,我认为是因为 else 中的最后一个 break 停止了 while 循环
    • @SMA 我完成了我的程序。我是初学者,我可以理解我在代码中做了什么,但是,我需要你解释一下这个代码序列:) String passwordInFile = map.get(user)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多