Can you figure this statement out?

Can someone helps me figure out a else statement for this program?

  • String[]names={"John", "Mike", "Jeff", "Eric"} String str="Mike" for(int i=0; i<names.length; i++) { if(names[i].equals(str) System.out.println(str + "occured at " + i) (I tried to set a else statement in the case the name didn't belong to the array in which case a message of the sort of println("doesn't appear in the name list") would return, but Im havin an error message instead...

  • Answer:

    First your code is incomplete so hard to say, are you getting the error just after you add your else? without else it runs properly? Second: you're not using ; at the end of your statements, but I guess it's just in your post and in the code you're doing it right? Third, my guess is you're trying to add the else after the loop which if that's the case of course you'll get error. You only can say it didn't appear in the list after you checked everything (after loop). Adding else right after if here would mean that it didn't appear at index i. If that's what you want to do, create a boolean variable before your loop and if the string appeard change it to true: boolean appeared = false; for(int i = 0; i < names.length; i++) { if(names[i].equals(str) { System.out.println(str + "occured at " + i); appeared = true; } } if(!appeared) System.out.println("doesn't appear in the name list");

Sweet Dreamer ♂ at Yahoo! Answers Visit the source

Was this solution helpful to you?

Other answers

You need to put the if inside of a try...catch block. it should look like this: String[]names={"John", "Mike", "Jeff", "Eric"} String str="Mike" for(int i=0; i<names.length; i++) { try { if(names[i].equals(str) System.out.println(str + "occured at " + i); } catch(Exception e) { System.out.println("doesn't appear in the name list"); }

Michael

Q&As still private I see. You'll get better results on this site if you make them public. Why keep the error message a secret? Copy & paste any error message that you're asking about.

modulo_function

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.