w3resource
Java Programming Exercies

Java Exercises: Reads a text and prints two words

Java Basic: Exercise-227 with Solution

Write a Java program which reads a text (only alphabetical characters and spaces.) and prints two words. The first one is the word which is arise most frequently in the text. The second one is the word which has the maximum number of letters.

Note: A word is a sequence of letters which is separated by the spaces.

Input:

A text is given in a line with following condition:
a. The number of letters in the text is less than or equal to 1000.
b. The number of letters in a word is less than or equal to 32.
c. There is only one word which is arise most frequently in given text.
d. There is only one word which has the maximum number of letters in given text.
Input text: Thank you for your comment and your participation.
Output: your participation.

Pictorial Presentation:

Java Basic Exercises: Reads a text and prints two words.

Sample Solution:

Java Code:

import java.util.Scanner;
class Main
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
         
        String strs[] = sc.nextLine().split(" ");
        int max_Length = 0;
        int indexL = 0;
        int max_Frequency = 0;
        int indexF = 0;
        System.out.println("Input a text in a line:");
        for (int i = 0; i < strs.length; i++)
        {
            if (max_Length < strs[i].length())
            {
                indexL = i;
                max_Length = strs[i].length();
            }
            int ctr = 0;
            for (int j = i; j < strs.length; j++)
            {
                if (strs[i].equals(strs[j]))
                {
                    ctr++;
                }
            }
            if (max_Frequency < ctr)
            {
                indexF = i;
                max_Frequency = ctr;
            }
        }
		System.out.println("Most frequent text and the word which has the maximum number of letters:");
        System.out.println(strs[indexF] + " " + strs[indexL]);
    }
}

Sample Output:

Thank you for your comment and your participation.
Input a text in a line:
Most frequent text and the word which has the maximum number of letters:
your participation.

Flowchart:

Flowchart: Reads a text and prints two words.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous:Write a Java program to print mode values from a given a sequence of integers. The mode value is the element which occurs most frequently. If there are several mode values, print them in ascending order.
Next: Write a Java program that reads n digits (given) chosen from 0 to 9 and prints the number of combinations where the sum of the digits equals to another given number (s). Do not use the same digits in a combination.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming