Hello good, previously I needed to make a code like this:
#Entrada (numero entero del 1 al 10)
#Salida en texto (se ha introducido el numero cinco
Example
#Introduzco el numero 6
#Haz introducido el numero "seis"
I discovered thanks to two users here that it could be done thanks to an array and a number that printed the position of the array that interested me thanks to the following code:
public static void main(String[]args) {
try (Scanner sc = new Scanner(System.in)) {
ArrayList<String> numeros = new ArrayList<String>();
numeros.add("Cero");
numeros.add("Uno");
numeros.add("Dos");
numeros.add("Tres");
numeros.add("Cuatro");
numeros.add("Cinco");
numeros.add("Seis");
numeros.add("Siete");
numeros.add("Ocho");
numeros.add("Nueve");
numeros.add("Diez");
int intro;
System.out.println("Introdue un numero del 1 al 10 para saber como se escribe");
intro = sc.nextInt();
if (intro > 10 && intro < 0){
System.out.println("Numero incorrecto");
}
else{
System.out.println(numeros.get(intro));
}
}
}
Now comes my problem and it is that I wanted to know if I can do the same thing but the other way around is to say that the user enters the number in letters and the program returns the whole number I mean:
#Introduzco el numero "seis"
#Haz introducido el numero 6
His thing would be not to do it with either if or switch unless there is no simpler alternative. Thanks in advance
To get the name of a number
You can define a string array with each value and then search by index:
And then:
The block
try ... catch
will allow your code to work by substituting each existing value in thenameOfNumbers
. So, if you wanted the , tooonce
, you add it in its proper position, at the end of the currentnameOfNumbers
. With himtry ... catch
you don't need this:if (intro > 10 && intro < 0){
but if it's a requirement of an exercise whatever, remove the blocktry ... catch
.It should be said that this works because in Java, as in almost all languages, arrays start at index
0
, so innameOfNumbers
we simply assign the name that would correspond to each numerical value. For more demanding programs, in which you need to convert any number to letters or vice versa, there are libraries that already do it 1 , taking into account aspects as changing as the language.To get the number from the letter
You can create a
HashMap
that associates each numeric value with a name (this in reverse would help you to solve what was stated in the first case).Then, you would look up the value associated with that key. For example:
Departure:
Grades
See for example the following:
ICU4J
translated
Integer-To-Words-Java
A somewhat cleaner alternative is to use the Java 8+ Optional.
Something like that:
And then, to invoke it, for example with the "four":
A good guide here: https://dzone.com/articles/using-optional-correctly-is-not-optional