-1

I am trying to compare the two String to check if the values are the same from a scanner input. The problem is that after the input of both of the values, the output is saying the two Strings are not the same.

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);
        }   
    }
}

I have tried this with multiple inputs, and the outcome is always they are not the same.

Any thoughts would be appreciated.

awesoon
  • 32,469
  • 11
  • 74
  • 99
afskymonkey
  • 17
  • 1
  • 4
  • Use the `equals()` or `equalsIgnoreCase()` method like `if(testOne.equals(testTwo)){...}` (depending upon your requirements) instead of using `==` (it compares object references and not the string text). – Lion May 31 '13 at 01:41

1 Answers1

0

Of cousre they are not the same. They are different instances so the == operator will mention this. However, testOne.equals(testTwo) should do the trick as this will not compare the pointers but the values instead.

Bernd Ebertz
  • 1,317
  • 8
  • 10