41.8k views
0 votes
20 pts, please write in JAVA. need this ASAP

In the Lesson Slides for this activity, we developed a method findChar for figuring out if a character was in a String.

The implementation was:

public boolean findChar(String string, String key)
{
for(int index = 0; index < string.length(); index++)
{
String character = string.substring(index,index+1);
if(character.equals(key))
{
return true;
}
}
return false;
}
However, there is a much more efficient and simple algorithm that we can use to determine if a character is in a String. Using the method signature public boolean findChar(String string, String key), figure out a more efficient method with a lower exection count.

Hint: We’ve learned a couple of methods that can tell us what index a character is at - can we use those to determine if the character is in a String?

1 Answer

4 votes

public class JavaApplication78 {

public boolean findChar(String string, String key){

if (string.contains(key)){

return true;

}

return false;

}

public static void main(String[] args) {

JavaApplication78 java = new JavaApplication78();

System.out.println(java.findChar("hello", "h"));

}

}

First I created the findChar method using the contains method. It checks to see if a certain sequence of characters is in another string. We returned the result. In our main method, we had to create a new instance of our main class so we could call our findChar method.

User Alex Zywicki
by
5.7k points