2014-12-08 24 views
0

我正在做登錄GUI。我遇到的問題是,當程序從我的記事本中讀取用戶名和密碼時,它會彈出保存在txt文件中的每行消息。例如,我的txt文件中有三組用戶名和密碼,當程序通過txt文件的第一行讀取時,如果第一組用戶名和密碼鍵匹配,則會彈出「登錄成功」,但如果輸入第二組密碼和用戶名,它會彈出「密碼不正確和用戶名」,在您確認之後,彈出「登錄成功」。夥計們,我需要你的幫助。 Thankss如何阻止程序讀取每一行並彈出每行的消息?

公共無效的actionPerformed(ActionEvent的五){

String inputUser = input1.getText(); 
    String inputPass = input2.getText(); 
    File loginf = new File("oop.txt"); 


     try{ 
      Scanner read = new Scanner(new File("oop.txt")); 


      while(read.hasNext()){ 
       String user = read.next(); 
       String pass = read.next(); 
       read.next(); 

      if(inputUser.equals(user) && inputPass.equals(pass)){  
        JOptionPane.showMessageDialog(this, "Login Sucessful"); 
        break; 
      } 

      else if(!inputUser.equals(user)&&!inputPass.equals(pass)){ 
       JOptionPane.showMessageDialog(null,"Incorrect Username and Password"); 
      } 
      } 



      read.close(); 
     } 
     catch (FileNotFoundException qwerty){ 
       JOptionPane.showMessageDialog(null, "Can't find a text file"); 
     } 

回答

2

讀取文件,直到你找到一個匹配,設置標誌或存儲你所需要的值,並打破循環,然後決定哪些消息顯示器

boolean youShallNotPass = true; 
while(read.hasNext()){ 
    String user = read.next(); 
    String pass = read.next(); 
    read.next(); 

    if(inputUser.equals(user) && inputPass.equals(pass)){  
     youShallNotPass = false; 
     break; 
    } 
} 

if(!youShallNotPass){  
    JOptionPane.showMessageDialog(this, "Login Sucessful"); 
} else { 
    JOptionPane.showMessageDialog(null,"Incorrect Username and Password"); 
} 
+0

'youShallNotPass'很有趣,但不需要很難閱讀。 ;)+1無論如何。 – robbmj 2014-12-08 05:13:26

+0

真的,也許'youBeGood'?這是下午四點三十分,我頭痛,我的工作很糟糕,這是我可以得到的所有幽默:( – MadProgrammer 2014-12-08 05:14:41

+0

謝謝,弟弟。它工作。你真的幫我很多 – 2014-12-08 05:27:47

相關問題