Answer to Question #303149 in Java | JSP | JSF for Tseser

Question #303149

Write a program to take a String as input then display the number of x characters word has in ascending order.

Example:

Enter a String

China is world most populous country

Number of 2 characters word : 1

Number of 4 characters word : 1

Number of 5 characters word : 2

Number of 7 characters word : 1

Number of 8 characters word : 1

Here, ascending is 2,4,5,7,8 don't return like 5,2,4,8,7

Hint: length(), charAt(), indexOf(), compareTo(), substring(), equals() can be used.

Note: Array, Split function as well as ternary operators i.e. ? : are not to be used.


1
Expert's answer
2022-02-28T13:53:51-0500
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.println("Enter a String:");
        Scanner in = new Scanner(System.in);
        String line = in.nextLine();
        for (int i = 1; i <= 100; i++) {
            int count = 0;
            String chopped = line;
            int spaceIndex;
            do {
                spaceIndex = chopped.indexOf(' ');
                if (spaceIndex != -1) {
                    if (chopped.substring(0, spaceIndex).length() == i) {
                        count++;
                    }
                    chopped = chopped.substring(spaceIndex + 1);
                }else{
                    if (chopped.length() == i) {
                        count++;
                    }
                }
            }
            while (spaceIndex != -1);
            if (count > 0) {
                System.out.println("Number of " + i + " characters word : " + count);
            }
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS