Check string value

Asked

Viewed 331 times

3

I wanted you to check if the entered value is vegetarian, and if it is, print on the user’s screen is vegetarian as follows the code, but when I type vegetarians or anything else it warns 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");
    }
    }
}

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 capitalized. Besides this you are not comparing two contents string but two references to strings that will obviously always be different:

import java.util.Scanner;

class Main {
    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();
        System.out.println(alimento.equals("Vegetariano") ? "É Vegetariano" : "nao é vegetariano");
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

The solutions:

  • Use equals() to compare the content and not the reference. The operator == only compares if both refer to the same memory location, which is impossible in this case.

  • Optionally you can make the string all to lower case before comparing to avoid slips in typing. The more normalized the text is, the easier it is to compare. For this it is possible to use the method toLowerCase() before comparing the content, or equalsIgnoreCase(), so kill both at once. So:

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

  • Ideally it should have an easier way of data entry to check and avoid errors. Asking someone to type a text to make a decision is asking for an error to happen. In these cases, a menu of options is used and the user enters a number, which is easier to compare.

  • 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

  • 1

    But in these cases there is no way to use the ==. Note that if you don’t mind typing problems just use the equals 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.

  • thank you very much xD

6

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.

  • Thank you very much for the answer but only for the question of my personal knowledge because I can’t apply it at work taking into account that I only had about 4 classes at hahahha college

  • 1

    @William’s intention is to give an alternative to other people who have a similar problem to use something more complex. Of course for a simple example it is not useful but it is a very interesting solution when the problem requires typing a text and small errors should be highlighted. This website seeks to provide solutions for all and not just for those who ask. Not everyone understands this. Not everyone understands the workings of website and that the important thing is to have a maximum quality and alternatives in the answers.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.