A
A
Anonymous Anonymous2020-02-09 17:42:53
Java
Anonymous Anonymous, 2020-02-09 17:42:53

How to get words with the same length in Java?

It is necessary to print to the console all words with the same length and with a consonant first letter.
I did the output of words with a consonant letter, but I still don’t understand how to do the length. I am new to Java, so can anyone please help.

import java.util.Scanner;
public class Subsequence {

    public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter text please:");
        String text = scanner.nextLine();
        System.out.println(text);

        String[] strArr = text.split(" ");
        StringBuilder sb = new StringBuilder();
            for (String s : strArr) {

                char c = s.charAt(0);
                if ((c != 'a') && (c != 'o') && (c != 'i') && (c != 'u') && (c != 'e') && (c != 'y'))
                {
                    sb.append(s).append(" ");
                }
                System.out.println(sb.toString());
            }
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Daniil Demidko, 2020-02-09
@Chronicler

I won't write the code for you, but I'll give you a hint. Both String and StringBuilder have a .length() method that returns the length.

C
Cheypnow, 2020-02-10
@Cheypnow

Filtering and grouping by number of characters per line:

String str = "aaa bbb eee ooooo yyyyy i ppp rrrr zzzzz";

        Predicate<String> isVowel = s -> s.startsWith("a")
                || s.startsWith("o")
                || s.startsWith("i")
                || s.startsWith("u")
                || s.startsWith("e")
                || s.startsWith("y");

        Map<Integer, List<String>> result = Arrays.stream(str.split(" "))
                .filter(s -> !isVowel.test(s))
                .collect(Collectors.groupingBy(String::length));

        System.out.println(result);

Conclusion:
{3=[bbb, ppp], 4=[rrrr], 5=[zzzzz]}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question