0

I'm trying to code a simple program for my friend who is obsessed with Sonic and the phrase "GOTTA GO FAST". The problem is, whenever I try to use scan.nextLine() as part of an if statement, it never works.

import java.util.Scanner;

public class meaningOfLife {
    static Scanner scan = new Scanner(System.in);
    private static String guessah = "Going fast";
    private static boolean areTheySmart = false;

    public static void howDoesOneGoFast(){
        while(!areTheySmart){
            System.out.println("What is the meaning of life? ");
            if(scan.nextLine() == guessah){
                System.out.println("YES");
                for(int i = 0; i >= 0; i++){
                    if(i < 10){
                        System.out.println("STARTING TO GO FAST");
                    } else if(i < 30){
                        System.out.println("GOING FAST");
                    } else if(i < 60){
                        System.out.println("GOING FASTER");
                    } else if(i < 100){
                        System.out.println("GOTTA GO FAST");
                    } else if(i < 150){
                        System.out.println("GOTTA GO FASTER");
                    } else{
                        System.out.println("FASTER FASTER FASTER FASTER FASTER");
                    }
                }
            } else{
                System.out.println("WRONG");
            }
        }
    }
    public static void main(String[] args){
        howDoesOneGoFast();
    }
}

At if(scan.nextLine() == guessah), the Scanner takes a String as input, and even if I copy-paste "Going fast" into the Scanner-field it doesn't properly copy it. I entered 'Going fast' into the scanner field at least 20 times, each with small variations but it still doesn't see it as an equal to "Going fast" (guessah's value).

tvkanters
  • 3,501
  • 4
  • 28
  • 45
  • When you compare strings, you should use the .equals() method, and not the operator == (as == compares the address under which the string is stored in memory) – Loïc Gammaitoni Jul 08 '14 at 16:16
  • `if(scan.nextLine().equals(guessah))` gotta use equals onstead of == when comparing object values (== is for comparing primitive values when dealing with primitive typesreferences, references when dealimg with objects). Or, you could intern() the string as soon as it comes through the scanner to check if it already exists in the String pool. If it does, == will work. – Dioxin Jul 08 '14 at 16:16
  • Thanks :) I was just about to close this question since I found the equals() method in the String Java API – user219709 Jul 08 '14 at 16:20

0 Answers0