if statement - How to assign numbers to words in java? -
i have problem lastly part of code. want assign numbers specific words 0 value, though strings first system.out.println correctly, cannot numerical equivalents of strings @ sec system.out.println.any ideas how solve problem?
public static double number; protected void mymethod(httpservletrequest request, httpservletresponse response) { string speech= request.getparameter("speech"); system.out.println("the recognized speech : "+ speech); // there no problem till here. if(speech == "hi") number = 1 ; if(speech== "thanks") number = 2 ; if(speech== "bye") number = 0 ; system.out.println("the number speech : " + number); }
however here dont right numbers 0 each word!
you can't utilize ==
operator check if 2 strings have same value in java, need utilize .equals()
or equalsignorecase()
methods instead:
if("hi".equalsignorecase(speech)) { number = 1; } else if("thanks".equalsignorecase(speech)) { number = 2; } else if("bye".equalsignorecase(speech)) { number = 0; } else { number = -1; }
the reason ==
operator compares references; homecoming true
if , if instance stored in variable speech
same instance literal string you've created between double quotes ("hi"
, "thanks"
, or "bye"
).
note utilize equalsignorecase()
phone call on literal string i'm declaring, rather variable assigned parameter. way, if speech == null
, method phone call still valid ("hi"
always string
), , won't nullpointerexception
, , flow go on until else
branch.
java if-statement methods numbers assign
No comments:
Post a Comment