What is wrong with this for/if statement?
for(int i=0; i<menuarraynum; i++) {
if(eatmenuarray[i] == eatchoice) {
System.out.println("success");
eat.consume(eatmenuarray[i]);
}
else {
System.out.println("failed " + (i+1) + " times");
}
}
I’ve been staring at it and making changes to it for about 40 minutes now, and I just can’t get it to work!
I have an array that contains 8 fields with some types of food in there. I type in "Pork" (it’s number 6 in the array) when I am prompted (input gets put on to the `eatchoice` variable) and it is supposed to send me to another method, but for some reason it fails every time, and all I see is "failed 1 times", "failed 2 times", etc etc. Can anyone help me out?
I’m guessing that eatmenuarray[] is an array of Strings? If so, you can’t compare String with ==. You need to do something like eatmenuarray[i].equals(eatchoice);
== will compare the objects to see if they are the same object. It will not compare the content of the object. A string is an object. And two strings can contain the same contents, but not actually be the same object. Hence, you cannot compare strings with ==. You have to use the equals() method.
April 23rd, 2011 at 8:20 am
wth i shound like its in a different language i dont understand it
sorry, good luck
References :
April 23rd, 2011 at 9:10 am
you cannot compare strings with ==
use equals
like this
if(eatmenuarray[i].equals(eatchoice))
if you want to ignore case then use
if(eatmenuarray[i].equalsIgnoreCase(eatchoice));
References :
April 23rd, 2011 at 9:31 am
I’m guessing that eatmenuarray[] is an array of Strings? If so, you can’t compare String with ==. You need to do something like eatmenuarray[i].equals(eatchoice);
== will compare the objects to see if they are the same object. It will not compare the content of the object. A string is an object. And two strings can contain the same contents, but not actually be the same object. Hence, you cannot compare strings with ==. You have to use the equals() method.
References :