2015-11-21 76 views
1

已解决!Java,将键盘输入值与file.txt值进行比较

我有一种功课,在那里我有一个文件,其中我的用户名和密码这样的:

user1的密码1

user2的密码2

用户3 password3

我需要使用FileInputStream类,我还需要键盘输入用户名和密码,并检查它是否已经存在(每个用户名必须匹配密码,在线)。我决定使用Map,但是......如果你看看我的while循环,我试图分解成key和value。我还创建了存储键盘输入的map2,并映射谁存储拆分键和值。

我的麻烦是这里:如果我输入用户名:user1,密码:password1,该条件如果(map.equals(map2))将返回true。但是,如果我输入用户名:user2和password:password2,即使user2和password2已经存在于我的文件中,“if”也会返回false。

提示:我不能覆盖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"); 
    } 

回答

0

你不应该比较两个地图。取而代之,比较地图中的值后,您将所有值存储在文件中,例如:

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

谢谢您的回复。但它不会工作......现在,如果我将我的.txt文件中的值设置为相同值,我会得到错误 – Linksx

+0

粘贴您的修改后的代码。 – SMA

+0

请看上面的内容,我发布了代码 – Linksx

相关问题