I imagine that it is a school exercise or something like, after all, present options for user choice textual way is not usually ideal for practical use.
As the question problem has already been solved by @Maniero, it follows by joke (by exaggeration factor) an answer based on distance from Levenshtein, who will find things with little differences of spelling:
import java.util.*;
import java.lang.*;
import java.io.*;
class Alimentos {
//http://rosettacode.org/wiki/Levenshtein_distance#Java
public static int distance(String a, String b) {
a = a.toLowerCase();
b = b.toLowerCase();
int [] costs = new int [b.length() + 1];
for (int j = 0; j < costs.length; j++)
costs[j] = j;
for (int i = 1; i <= a.length(); i++) {
costs[0] = i;
int nw = i - 1;
for (int j = 1; j <= b.length(); j++) {
int cj = Math.min(
1 + Math.min(costs[j], costs[j - 1]),
a.charAt(i - 1) == b.charAt(j - 1) ? nw : nw + 1
);
nw = costs[j];
costs[j] = cj;
}
}
return costs[b.length()];
}
public static void main(String args[]){
String[] alimentos = new String[4];
alimentos[0] = "Vegetariano";
alimentos[1] = "Peixe";
alimentos[2] = "Frango";
alimentos[3] = "Carne";
String alimento;
String resultado;
int distancia;
int prevDistancia;
Scanner in = new Scanner(System.in);
System.out.println("Digite o Alimento (Vegetariano, Peixe, Frango ou Carne): ");
while ( in.hasNext() ) {
alimento = in.nextLine();
prevDistancia = 99999; // Valor maior do que qq distancia possivel aqui
resultado = "";
for ( String item : alimentos ) {
distancia = distance( item, alimento );
if ( prevDistancia > distancia ) {
prevDistancia = distancia;
resultado = item;
}
}
System.out.println("Alimento: "+resultado );
}
}
}
Taking advantage, I modified the code to accept several entries then, until the user leaves the line blank, and in the output appear the four options, not just Vegetarian.
Example entries, purposely spelled differently from code:
Framgo
Pexe
Vegetais
Carnes
Results:
Digite o Alimento (Vegetariano, Peixe, Frango ou Carne):
Alimento: Frango
Alimento: Peixe
Alimento: Vegetariano
Alimento: Carne
See working on IDEONE.
I know it’s the worst way to do it, but it’s like the college teacher demanded rsrs. We haven’t learned this equals yet so I didn’t use and tried the
==
rsrs– GGirotto
But in these cases there is no way to use the
==
. Note that if you don’t mind typing problems just use theequals
this is the only secret really needed to make your code work. Of course any typo will be a problem. I’ll even change the answer to make it optional, since this isn’t really necessary for your solution.– Maniero
thank you very much xD
– GGirotto