Hello, I would like to know how I can obtain which word appears first in the dictionary, from two words that a user enters in java. Thank you very much. For example, if the user enters the word hola
and the word adiós
, what would be the method to know which of the 2 appears first in the diccionario
.
private static Scanner sc;
private static String pidePalabra1() {
System.out.print("Introduzca una palabra: ");
return sc.nextLine();
}
private static String pidePalabra2() {
System.out.print("Introduzca otra palabra");
return sc.nextLine();
}
private static void muestraInfo(String palabra1, String palabra2) {
System.out.printf("Palabra1: %s \tPalbra2: %s = %s")
}
public static void main(String[] args) {
sc = new Scanner (System.in);
String palabra1 = pidePalabra1();
String palabra2 = pidePalabra2();
muestraInfo (palabra1, palabra2);
}
}
How are words organized in the dictionary?
It is sorted from the first letter of the word. When words begin with the same letter, the second letter is also taken into account. When they coincide in the first two or more letters, they are ordered taking into account the third, the fourth, and so on...
then to do this you could use the compareTo() method which compares two strings
lexicográficamente
. If you want to compare strings that contain capital letters, it may be more feasible to use the compareToIgnorecase methodExample: