views:

445

answers:

5

How do i write an if statement in Java that displays Goodbye! if the variable word contains a letter d?

Thanks to everyone.

+15  A: 

if(word.contains("d"))
{
    System.out.println("Goodbye!");
}

marcos
+4  A: 

Use:

if(word.indexOf("d") >= 0) {
  System.out.println("Goodbye!");
}
OMG Ponies
+1 simply because this is the only answer so far that includes the braces.
Jeremy Cron
should be "... word.indexOf("d") >= 0 ..."
Chris
I believe indexOf('d') would be more efficient than indexOf("d") - note the use of the indexOf method that takes a char instead of a String.
Thomas Owens
@Thomas: How would you prove that?
OMG Ponies
@Thomas: Parse in a dictionary and find out which one takes longer. ;P
Drew
+1  A: 

Look up the Java API docs to see what is available in the String class. There are several options including the indexOf() method that returns -1 if the given character is not in the String and an index of the character if it is found in the String.

 int ans = mystring.indexOf(mychar);

You can then use an if statement to check the ans variable.

Vincent Ramdhanie
that would be very annoying. In C / C++ not so much, but Java uses booleans.
Tom
@Tom in Java you will have to do if(ans == -1) etc.
Vincent Ramdhanie
+1  A: 
if (word.contains("d")) System.out.println("Goodbye!");

Well, that was in Java!!

Suraj Chandran
On what version of java did they introduce the 'contains' method for String?
Kushal Paudyal
I guess JDK5 onwards
Suraj Chandran
A: 
if(word.compareTo("d") == 0)
   System.out.println("Goodbye!");

or

if(word.equals("d"))
  System.out.println("Goodbye!");

That's assuming of course that word is a String and not a char.

ChadNC
that is wrong, it will compare the whole string, not if it contains "d".
marcos
I read what he was asking incorrectly. I thought he meant he had a String variable named 'word' that he was wanting to check if it's contents was 'd' when he was wanting to find out if a String variables contents had a 'd' in it somewhere. My bad.-2 haha
ChadNC