Write a program to input a sentence and print the numbers of characters found in the longest word of the given sentence.
At first import the util pacakage for creating the object of the scanner class. Now create an object (sc) of Scanner class. Read the sentence using nextLine() method of Scanner class. Now split the sentence into words using split() method and store into a string array. Now set a variable max and initialized to 0. Now check all the words and compare the length of the word and max variables and store the maximum length of the word and print it.
import java.util.*; public class longestWord { public static void main() { Scanner sc=new Scanner(System.in); System.out.println("Enter a Setance : "); String str=sc.nextLine(); String []words=str.split(" "); int max=0; String res=""; for(int i=0;imax) { max=words[i].length(); res=words[i]; } } System.out.print("Maximum Length of the words is : " + max); System.out.print("Maximum Length words is : " + res); } }
Enter a Setance :
People prefer electric vehicles over conventional ones
Maximum Length of the words is : 12
Maximum Length words is : conventional