KnowledgeBoat Logo
|
LoginJOIN NOW

Computer Applications

Write a program by using scanner class to input a sentence. Display the longest word along with the number of characters in it.

Sample Input:
We are learning scanner class in Java

Sample Output:
The longest word: learning
Number of characters: 8

Java

Input in Java

ICSE 2009

31 Likes

Answer

import java.util.Scanner;

public class KboatLongestWord
{
    public static void main(String args[]) {
       Scanner in = new Scanner(System.in);
       System.out.println("Enter a word or sentence:");
       String str = in.nextLine();
       str += " ";
       String word = "", lWord = "";
       
       for (int i = 0; i < str.length(); i++) {
           if (str.charAt(i) == ' ') {
               
                if (word.length() > lWord.length())
                    lWord = word;
                    
                word = "";
           }
           else {
               word += str.charAt(i);
           }
       }
       
       System.out.println("The longest word: " + lWord);
       System.out.println("Number of characters: " + lWord.length());
    }
    
}

Variable Description Table

Program Explanation

Output

BlueJ output of Write a program by using scanner class to input a sentence. Display the longest word along with the number of characters in it. Sample Input: We are learning scanner class in Java Sample Output: The longest word: learning Number of characters: 8

Answered By

7 Likes


Related Questions