Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
outputting a sentence from shortest word to longest

This is what I currently have been trying to get an output like this:

input:  this is a sentence
output: a is this sentence
import java.util.Scanner;
Scanner input = new Scanner(System.in);
        System.out.print("Enter a sentance:");
        String text = input.nextLine();
        String[] words = text.split("");
        String temp;

        for (int i = 0; i < words.length; i++) {
            for (int j = 0; j < (words.length - 1); j++) {
                if (words[j].compareTo(words[j + 1]) < 0) {
                    temp = words[j];
                    words[j] = words[j + 1];
                    words[j + 1] = temp;

                }
            }
            System.out.print(words[i]);
        }
    }
}

If anyone could help that would be great!

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You may convert the input to a list and then sort using a lambda:

Scanner input = new Scanner(System.in);
System.out.print("Enter a sentence:");
String text = input.nextLine();
List<String> words = Arrays.asList(text.split(" "));
words.sort(Comparator.comparingInt(String::length));
System.out.println(String.join(" ", words));

This prints (for input this is a sentence):

 a is this sentence
over 4 years ago · Santiago Trujillo Relatório

0

@Test
    public void testSort() {
        Assertions.assertEquals("a is this sentence", sort("this is a sentence"));
    }

    private String sort(String sentence) {
        return Arrays.stream(sentence.split(" "))
                .sorted(Comparator.comparingInt(String::length))
                .collect(Collectors.joining(" "));
    }

// split words by space then sort by length and join words again by space.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda