91.9k views
1 vote
Write a Comparator that compares String objects by the number of words they contain. Consider any nonwhitespace string of characters to be a word. For example, "hello" comes before "I see", which comes before "You can do it"

User Drexin
by
5.4k points

1 Answer

4 votes

Answer:

import java.util.Scanner;

public class num12 {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.println("Enter the first String");

String word1 = in.nextLine();

System.out.println("Enter the second String");

String word2 = in.nextLine();

System.out.println("Enter the third String");

String word3 = in.nextLine();

//Remove all white spaces

String cword1 = word1.replace(" ","");

String cword2 = word2.replace(" ","");

String cword3 = word3.replace(" ","");

//Comparing the string by their lengths

if(cword1.length()>cword2.length()&&cword1.length()>cword3.length()){

System.out.println(word1+" Is the longest");

}

else if(cword2.length()>cword1.length()&&cword2.length()>cword3.length()){

System.out.println(word2+" Is the longest");

}

else{

System.out.println(cword3+" Is the longest");

}

}

}

Step-by-step explanation:

Using Java Programming Language

Use the Scanner Class to obtain the String values from the user

Save them in different variables

Use the replace() method in java to remove white space from any of the string entered

Using if and else statements compare the lengths of the strings (word.length()) returns the length of the word.

Print out the word that is longest

NOTE I have compared three Strings, comparing two would have been more straigth forward

User Robb Vandaveer
by
6.0k points