-1

So, pretty extreme newb. Just a heads up.

Here's the assignment that I'm working on:

Write a method that accepts a large string. This method will return true if the string starts with the word "Java". This word can be any variation with uppercase or lowercase letters.

java Java jAva jaVa javA JAva JaVa JavA jAVa jAvA jaVA JAVa JaVA jAVA JAVA are all of the possibilites.

And this is the code that is given to start:

public class Problem16 {
    public static void main(String[] args) {
        System.out.println(startsWithJava("JavaTest")); // True
        System.out.println(startsWithJava("JaVaTest")); // True
        System.out.println(startsWithJava("TestJava")); // False
        System.out.println(startsWithJava(" JavaTest")); // False
    }

    public static boolean startsWithJava(String phrase) {
        // Your code here
    }
}

And so far this is where I'm at:

    public static boolean startsWithJava(String phrase) {
    
        String[] java = {"java","Java","jAva","jaVa","javA","JAva","JaVa","JavA","jAVa","jAvA","jaVA","JAVa","JaVA","jAVA","JAVA"};
    
        for (int i = 0; i < java.length; i++) {
            if (phrase.substring(0, 3) == java[i])
                return true;
        }
    }   

So I'm thinking I need to figure out a different way to do it, because I'm having trouble figuring out how to properly get a boolean return statement outside of the for loop.

Appreciate the help in advance!

  • `phrase.toLowerCase().startsWith("java")` – MadProgrammer Mar 29 '22 at 02:13
  • 1
    As an aside, it's very important that you _don't_ use `==` to check for String equality! See [this Stack overflow question](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) for more, but basically, use `equals(Object)` instead. For your particular problem, you don't need equality at all (as others have said), but this is an important thing to get right in the future. – yshavit Mar 29 '22 at 04:37
  • Always search Stack Overflow thoroughly before posting. – Basil Bourque Mar 29 '22 at 04:40
  • That also should have been `if (phrase.substring(0, 4).equals(java[i]))`...note the `4` and `.equals()`. – Idle_Mind Mar 29 '22 at 04:42

1 Answers1

1

Method toLowerCase and method startsWith, both in class java.lang.String.

public static boolean startsWithJava(String phrase) {
    return phrase.toLowerCase().startsWith("java");
}
Abra
  • 19,142
  • 7
  • 29
  • 41