Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This code is for Java , I usually use Dr.Java as my platform to write these. Im

ID: 3759861 • Letter: T

Question

This code is for Java, I usually use Dr.Java as my platform to write these. Im a beginner so comments on what you did will be really helpful. Also, if possible, please use simple syntax. Thanks so much. Will rate life saver

Write a static method named longestWord that accepts a string as its parameter and returns the length of the longest word in the string. A word is a sequence of one or more non-space characters (any character other than the space character, ' ' ).

Here are some example calls to your method and their expected results:

Call Value returned

longestWord("to be or not to be") 3

longestWord("oh hello, how are you?") 6

longestWord("I am OK") 2

longestWord(" this example has many spaces ") 7

longestWord("test") 4

longestWord("") 0

longestWord(" ") 0

Note that the string might be empty, might not contain any words, might begin with spaces, and might contain words separated by multiple spaces. You may assume that the string doesn't contain any other whitespace characters such as tabs or newlines. You may not use auxiliary objects such as Scanner or StringTokenizer to solve this problem.

Explanation / Answer

public class HelloWorld{
static int longestWord(String str){
if(str.length()==0){
  
return 0;
}else if(str.matches(".*[a-zA-Z]+.*")){
String[] words=str.split(" ");
int max=words[0].length();
for(int i=0;i<words.length;i++){
if(max<words[i].length()){
max=words[i].length();
}
}
return max;
}else{
return 0;
}
}
public static void main(String []args){
System.out.println(longestWord("I am OK"));
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote