1

My second scanner input get stored as desired but still the if condition comparing correctString == stringValue is not executed. Could you help.

{

static String stringValue = "A";
public static void main(String[] args) {
    int time;
    time = speedType();
    //System.out.println(time);
}
private static int speedType() {
    System.out.println("Let's play a game\nHow fast can you type \"I type very quickly\" \nPress Enter then type the statement and then press Enter again");
    Scanner scanner = new Scanner (System.in);
    String string = scanner.nextLine();
    if(string.equals("")){
        Date startTime = new Date();
        System.out.println("Start:\n");
        String correctString = scanner.nextLine();
        System.out.println(correctString);
        if (correctString == stringValue){
            Date endTime = new Date();
            System.out.println(endTime);
        }
        else
            System.out.println("Please enter correct string");
    }
    return 0;       



}}
CtrlV
  • 115
  • 11

1 Answers1

1

Regarding,

if (correctString == stringValue){

Don't compare Strings using ==. Use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two objects are the same which is not what you're interested in right now. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead of

if (fu == "bar") {
  // do something
}

do,

if ("bar".equals(fu)) {
  // do something
}

or,

if ("bar".equalsIgnoreCase(fu)) {
  // do something
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Oh that was really quick. Almost like googling ...Ya it worked. And I understood what you mentioned. Thanks :) – CtrlV Jun 09 '13 at 17:39
  • @CtrlV: you're welcome. I have this answer in a text file with other stock answers since it gets asked so often. – Hovercraft Full Of Eels Jun 09 '13 at 17:41
  • 1
    @CtrlV I just wonder why you used *equals* in `if(string.equals(""))` but not in `if (correctString == stringValue)` :) – Pshemo Jun 09 '13 at 17:43