I need to make a class that takes 3 user phrases and prints in order from the shortest sentence to the longest:
Make a program to read three user phrases and display on the screen the three sentences in order of sentence size. For example: Suppose the user provided the following phrases:
Today I was happy 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 2 ways:
1: Using array and Collections.sort that I searched 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 vector of strings and ifs. I was able to print the smallest of all but I have no idea how to proceed, I could facilitate this process using Math.min (phrase1.length (), Math.min (phrase2.length (), frase3.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've been trying to do all day, I do not know how a seemingly so easy exercise is taking me so long.