2014-10-19 2 views
0

조합 잠금을 요청하는 APCS 클래스에 할당이 있으며 기본 구조가 다운 된 것 같습니다. 그러나 나는 계속 nextLine()String을 비교하지 못하게하는 문제에 직면 해있다.String에 nextLine()을 비교하는 방법

nextLine()이 기본값 인 경우 int s입니까? 아니면 누군가 내 코드에 무엇이 잘못되었는지 말해 줄 수 있습니까?

if((in.nextLine()).compareTo(combo)) 
    { 
     System.out.println("The lock is now unlocked."); 
     System.out.println("Please enter the combo to unlock: "); 
     if((in.nextLine()).compareTo(combo)) 
     { 
      System.out.println("The lock is now locked."); 

     } 
     else 
     { 
      System.exit(0); 
     } 
    } 

p.s. ide는 오류를 반환합니다. "호환되지 않는 유형 : int는 부울로 변환 될 수 없습니다."라는 if 조건을 참조합니다.

답변

3

nextLine()은 항상 String을 반환하므로 문제가되지 않습니다. 문자열이 전적으로 동일한 경우 str 0에 비교되는 값보다 사전 작거나 str 경우 양수가 비교되는 값보다 사전 이상이면

compareTo(str)는 음수를 반환한다.

equals(str)을 사용하려는 경우 부울 값을 반환합니다.

+0

고맙습니다. 지금 문제가되었습니다. –

2

compareTo()는 부울이 아닌 정수 값을 반환합니다.

은 (http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html에서, Comparable 인터페이스에서)은 compareTo를위한 자바 API 문서를 참조하십시오

Method Detail

compareTo

Returns: a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

두 개의 문자열을 비교하는 가장 간단한 방법은 또 다른 함정에 조심

if (in.nextLine().equals(combo)) { /* code here */ } 

을 사용하는 것입니다 이 프로그램도. 첫 번째 nextLine()과 두 번째 nextLine()은 실제로 두 개의 별도 입력 행입니다. nextLine()은 독자가 입력 한 다음 줄을 반환하므로 호출 할 때마다 다른 입력 줄이 반환됩니다. 해결책은 nextLine()의 결과를 변수로 저장하는 것입니다.

String enteredCombo = in.nextLine(); 
if (enteredCombo.equals(combo)) 
{ 
    System.out.println("The lock is now unlocked."); 
    System.out.println("Please enter the combo to lock: "); 
    enteredCombo = in.nextLine(); 
    if(enteredCombo.equals(combo)) 
    { 
     System.out.println("The lock is now locked."); 
    } 
    else 
    { 
     System.exit(0); 
    } 
}