Check string value

3

I wanted you to check if the value entered is vegetarian, and if it is, print on the user's screen is vegetarian as the code follows, however when I type vegetarians or anything else it alerts you that it is not.

import java.util.Scanner;
public class Alimentos {
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
        System.out.println("\nDigite o Alimento (Vegetariano, Peixe, Frango ou Carne): ");
        String alimento = in.nextLine();
        if(alimento == "Vegetarianos"){
        System.out.println("É Vegetariano");
    } else {
        System.out.println("nao é vegetariano");
    }
    }
}
    
asked by anonymous 22.03.2015 / 21:04

2 answers

6

The code has some problems. You are asking to type in the singular and comparing with the plural. And worse, it has to be with the first letter in capital letters. In addition you are not comparing two string contents but rather two references to strings that will obviously always be different:

import java.util.Scanner;
class Ideone {
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
        System.out.println("\nDigite o Alimento (Vegetariano, Peixe, Frango ou Carne): ");
        String alimento = in.nextLine();
        if(alimento.equals("Vegetariano")) {
            System.out.println("É Vegetariano");
        } else {
            System.out.println("nao é vegetariano");
        }
    }
}

See running on ideone .

The solutions:

  • Use equals() to compare the content, not the reference. The == operator compares only if both refer to the same memory location, which is impossible in this case.
  • Optionally you can make string whole to lowercase before comparing to avoid slips in typing. The more standardized the text is, the easier it is to compare. For this you can use the toLowerCase() method. before comparing the content, or equalsIgnoreCase() , so kill both things at once. So:

    alimento.toLowerCase().equals("vegetariano") // OU
    alimento.equalsIgnoreCase("Vegetariano")
    
  • Optionally compare everything in lowercase and do not have the discrepancy of uppercase V and S at the end. If you leave it written in a specific way, it should always be typed that way. If it will not normalize, then it should compare exactly with the text you ask to type. If V is uppercase, it must be in both places, if it is in the singular, it must be in both places.

  • Ideally you should have an easier way to enter data to check and avoid errors. Asking for someone to type text to make a decision is to ask for a mistake to happen. In these cases, you usually use a menu of options and the user types a number, which is easier to compare.
22.03.2015 / 21:21
6

I imagine it to be a school exercise or something, after all, presenting options to choose the user in a textual way is generally not ideal for practical use.

As the problem of the question has already been solved by @bigown, a response based on Levenshtein's distance, which will find things with small differences in spelling, follows as a joke (by the exaggeration factor):

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 of it, I modified the code to accept several entries then until the user left the line blank, and in the output the four options, not just Vegetarian, appear.


Example entries, purposely spelled differently than code:

Framgo
Pexe
Vegetais
Carnes

Results:

Digite o Alimento (Vegetariano, Peixe, Frango ou Carne): 
Alimento: Frango
Alimento: Peixe
Alimento: Vegetariano
Alimento: Carne

See working at IDEONE .

    
22.03.2015 / 21:52