2
I need to make a class that receives 3 user sentences and prints in order from the smallest sentence to the largest:
Make a program to read three user phrases and show on screen the three sentences in order of sentence size. For example: Suppose the user provided the following phrases:
- Today I was cheerful
- Today is Friday
- Yesterday I was very sad
The result of the program would be:
Hoje é sexta Hoje eu fiquei alegre Ontem eu estava bem triste
I’ve tried two ways:
1: Using array and Collections.Sort I searched on the net and could not even understand
package exercicio1;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.JOptionPane;
public class App {
public static void main(String[] args) {
ArrayList<String> lista = new ArrayList<String>();
lista.add(JOptionPane.showInputDialog("Frase 1:"));
lista.add(JOptionPane.showInputDialog("Frase 2:"));
lista.add(JOptionPane.showInputDialog("Frase 3:"));
Collections.sort(lista);
for(int i = 0; i < lista.size(); i++){
System.out.println(lista.get(i));
}
}
}
2: Using a Strings and ifs array. Obs. I managed to print the smallest of all but I have no idea how to proceed, I could facilitate this process using Math.min(frase1.length(), Math.min(frase2.length(), frase3.length length());
package exercicio1;
import javax.swing.JOptionPane;
public class App {
public static void main(String[] args) {
String[] frases = new String[3];
String frase1 = JOptionPane.showInputDialog("Frase 1:");
String frase2 = JOptionPane.showInputDialog("Frase 2:");
String frase3 = JOptionPane.showInputDialog("Frase 3:");
if(frase1.length() < frase2.length() && frase1.length() < frase3.length()){
frases[1] = frase1;
}else{
if(frase2.length() < frase1.length() && frase2.length() < frase3.length()){
frases[1] = frase2;
}else{
if(frase3.length() < frase1.length() && frase3.length() < frase2.length()){
frases[1] = frase3;
}
}
}
System.out.println(frases[1]);
}
}
I’m all day trying to do, I don’t know how a seemingly easy exercise is taking me so long
The first way is very simple, just compare the list strings with Comparator.
– user28595