I have a problem about the last part of the code. I want to assign numbers to specific words but i always get 0 value, even though I get those strings from the first System.out.println correctly, i cannot get the numerical equivalents of those strings at the second System.out.println.Any ideas how to solve this problem?
public static double number;
protected void myMethod(HttpServletRequest request, HttpServletResponse response) {
String speech= request.getParameter("speech");
System.out.println("The recognized speech is : "+ speech);
// There is no problem till here.
if(speech == "Hi")
number = 1 ;
if(speech== "Thanks")
number = 2 ;
if(speech== "Bye")
number = 0 ;
System.out.println("The number for the speech is : " + number);
}
However here i dont get the correct numbers but only 0 for each word!
You can’t use the
==operator to check if two Strings have the same value in Java, you need to use the.equals()orequalsIgnoreCase()methods instead:The reason for this is that the
==operator compares references; that is it will returntrueif and only if the instance stored in variablespeechis the same instance as the literal String you’ve created between double quotes ("Hi","Thanks", or"Bye").Note also that I use the
equalsIgnoreCase()call on the literal String I’m declaring, rather than the variable that is assigned from the parameter. This way, if aspeech == null, the method call is still valid ("Hi"will always be aString), and so you won’t get aNullPointerException, and the flow will continue until theelsebranch.