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"));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.