2017-05-06 10 views
-1

사용자 입력과 파일 내용을 비교하려고했습니다. 이 프로그램은 특정 파일을 읽고 사용자의 문자열 입력을 검사합니다. ArrayList를 사용자 입력과 비교하는 데 문제가 있습니다.ArrayList와 사용자 입력 비교

공용 클래스 btnLoginListener는 리스너 {

@Override 
    public void handleEvent(Event arg0) 
    { 

     //variables for the class 
     username = txtUsername.getText(); 
     password = txtPassword.getText(); 

     MessageBox messageBox = new MessageBox(shell, SWT.OK); 

     try { 
      writeFile(); 
      messageBox.setMessage("Success Writing the File!"); 
     } catch (IOException x) 
     { 
      messageBox.setMessage("Something bad happened when writing the file!"); 
     } 

     try { 
      readFile("in.txt"); 

     } catch (IOException x) 
     { 
      messageBox.setMessage("Something bad happened when reading the file!" + x); 
     } 

     if (username.equals(names)) 
     { 
      messageBox.setMessage("Correct"); 
     } 
     else 
     { 
      messageBox.setMessage("Wrong"); 
     }  

     messageBox.open(); 
    } 
} 

private static void readFile(String fileName) throws IOException 
{ 
    //use . to get current directory 
    File dir = new File("."); 
    File fin = new File(dir.getCanonicalPath() + File.separator + fileName); 

    // Construct BufferedReader from FileReader 
    BufferedReader br = new BufferedReader(new FileReader(fin)); 


    String line = null; 
    while ((line = br.readLine()) != null) 
    { 
     Collections.addAll(names, line); 
    }  

    br.close(); 
} 
+1

'ArrayList와 사용자 입력을 비교하는 데 문제가 있습니다.' 조금 더 설명해주십시오. 예외 일 경우 스택 추적을 공유하십시오. –

+0

어디에서 왔는지 설명 할 수 있습니까? –

+0

이름의 유형은 무엇입니까? 사용자 이름의 유형은 무엇입니까? 목록 및 문자열이 의심됩니다. 문자열이 목록 과 어떻게 같을 수 있습니까? 무엇을 성취하려고합니까? "비교"와 "대조"를 정의해야합니다. –

답변

0

난 당신이 요소 exists 여부 list에서 확인하려고하는 가정하고 구현합니다. 그렇다면 contains 메서드 here's Javadoc을 사용해야합니다.

따라서 if (username.equals(names))을 사용하는 대신 if (names.contains(username))을 사용할 수 있습니다.

는이 외에도에서, 당신은 다음과 같이 변경한다 :
  • 파일을 이벤트가 호출 될 때마다 읽을하지 마십시오. 정적 파일을 읽으면서 한 번 읽고 나서 ArrayList에 저장할 수 있습니다.
  • 변수를 usernamepassword으로 만듭니다.
  • writeFile() 호출은 각 이벤트에 동적 값을 추가하거나 쓰지 않는 한 제거하십시오.