-1

I was wondering how I should write this if statement in my assignment. The question is:
Print option 2 if one of the strings begins with the letter w or has 5 characters.

I would use the .contains to find the "w".

if (two.contains("w") {
System.out.println(two);

but the one with the characters I am unsure how to find the method.

GURU Shreyansh
  • 881
  • 1
  • 7
  • 19
Emma
  • 15
  • 1
  • Class `String` has many useful methods (such as `contains`, and many other ones), including a method to get the length of the string. See the [documentation of class `String`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html) and find the method that you could use for this. – Jesper Jul 13 '21 at 13:26
  • 4
    First of all, it says `[...] begins with the letter "w"` which would translate to `two.startsWith("w")`. The length of a string can be retrieved using `length()`: `if (two.startsWith("w") || two.length() == 5)` – Felix Jul 13 '21 at 13:26
  • if a string has 5 characters, its **length** is 5. `pwet` contains `w`but doesn't **start with** `w` ? – jhamon Jul 13 '21 at 13:26
  • you will need to loop over the list/array of string and like @jesper said you can use the find method on the string or in this instance better to try the startsWith() method. – Rob Jul 13 '21 at 13:28
  • Here's a basic [intro to java String](https://www.youtube.com/watch?v=yXtoSrGDkuc) that you might find helpful. – jarmod Jul 13 '21 at 13:29

2 Answers2

0

If you have a List or Set, you may need to loop over them one by one, to do the actual comparing try this:

(two.startsWith("w") || two.length() == 5) {
     System.out.println(two);
}

The first condition checks if given String object starts with given char, and the other one counts the number of characters in the String and checks your desired lenght, which is 5.

For more useful information and String object has, check this out String (Java Platform SE 7)

Tomino
  • 475
  • 2
  • 15
0
String aString = ".....";

if (aString.startsWith("w") || aString.length() == 5) {
    System.out.println("option 2");
}

The method .contains returns true if find a substring (in this case "w") in string. You should use .startsWith method.

djm.im
  • 3,295
  • 4
  • 30
  • 45