-3

hey im making a program in java were you type into a console then it responds back with the computer actually talking(with sound), im using the FreeTTs speech synthesizer. For some reason when i write the following code its output not what i want.

import java.util.Scanner;

import com.sun.speech.freetts.VoiceManager;
import com.sun.speech.freetts.Voice;

public class TextToSpeech {
    public static void main(String args[]){

         Scanner input = new Scanner(System.in);
         String userInput = input.nextLine();

         if(userInput == "hi"){
         Voice v;
         VoiceManager vm=VoiceManager.getInstance();
         v=vm.getVoice("kevin16");
         v.allocate();
         v.speak("Hey my name is jarvis");
         input.close();
         }else
             System.out.println("you suck try again");
    }

}
Nivas
  • 18,126
  • 4
  • 62
  • 76
RhysBuddy
  • 125
  • 3
  • 11
  • 2
    `if(userInput.equals("hi")) {` will properly compare your strings. – Archibald Jun 24 '14 at 14:27
  • 1
    You should never compare Strings with ==. Use .equals() instead – NickJ Jun 24 '14 at 14:27
  • The reason behind Archer's comment is the == comparison only compares the storage location of two objects. While in Java Strings are immutable, its still possible that the actual data location of two String can be different. '.equals' will check the objects "contents" rather than the storage location, guaranteeing that equals will return true to your if statement. – Jason Jun 24 '14 at 14:29
  • Thanks guys ,worked perfectly – RhysBuddy Jun 24 '14 at 14:34

1 Answers1

1

When you compare reference variables (String reference variables in your instance) the == comparison operator checks whether they refer to the same object. For example;

String s = new String("s");
String s2 = "s";
System.out.println(s==s2);

The above outputs false because s and s2 do not refer to the same String object in memory;

Instead, use the .equals() method to compare whether your String references are meaningfully equal. For example;

String s = new String("s");
String s2 = "s";
System.out.println(s.equals(s2));

The above outputs true.

Rudi Kershaw
  • 12,332
  • 7
  • 52
  • 77