2013-05-31 3 views
0

값이 스캐너 입력과 동일한 지 확인하기 위해 두 String을 비교하려고합니다. 문제는 두 값을 모두 입력 한 후 결과가 두 문자열이 같지 않다는 것입니다.스캐너 문자열 입력과 비교

import java.util.Scanner; 

public class Test { 

    public static void main(String[] args) { 

     String testOne = ""; 
     String testTwo = ""; 

     Scanner input = new Scanner(System.in); 
     testOne = input.next(); 

     Scanner inputOne = new Scanner(System.in); 
     testTwo = inputOne.next(); 

     System.out.println("Before comapring: testOne = " + testOne + "\t testTwo = " + testTwo +"\n"); 

     if(testOne == testTwo){ 
      System.out.println("The same"); 
      System.out.println("After comparing: TestOne = " + testOne + "\t testTwo = " + testTwo); 
     } 
     else{ 
      System.out.println("Not The same"); 
      System.out.println("After comparing: testOne = " + testOne + "\t testTwo = " + testTwo); 
     } 
    } 
} 

여러 개의 입력을이 시도했으며, 결과는 그들이 동일하지 않습니다 항상.

어떤 생각을 감상 할 수있다. cousre의

+0

'=='대신에'if (testOne.equals (testTwo)) {...}'와 같은'equals()'또는'equalsIgnoreCase()'메소드를 사용하십시오 문자열 참조가 아닌 객체 참조). – Lion

+0

도움을 주셔서 감사합니다. 그것은 그 문제를 해결했습니다. – afskymonkey

답변

1

그들은 같은하지 않습니다. 그것들은 다른 인스턴스이므로 == 연산자가 이것을 언급 할 것입니다. 그러나 testOne.equals(testTwo)은 포인터를 비교하지 않고 대신 값을 비교하기 때문에 트릭을 수행해야합니다.