1
我有一種功課,在那裏我有一個文件,其中我的用戶名和密碼這樣的:
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");
}
謝謝您的回覆。但它不會工作......現在,如果我將我的.txt文件中的值設置爲相同值,我會得到錯誤 – Linksx
粘貼您的修改後的代碼。 – SMA
請看上面的內容,我發佈了代碼 – Linksx