#Java: How to check if a value is part of an enum?

1 messages · Page 1 of 1 (latest)

spark knoll
#

I want to check if a input value coincide with an enum, I tried something, but I not believe what be the correct way:

import java.util.Scanner;

public class Ejercicio_1{

Scanner key=new Scanner(System.in);

public void Nombrar(){

    enum Nombres{
        Alejandra,Leonardo,Rosa,Guillermo,Gabriel,Daniel,Luisa,Ludmila
    }

   String[] nombre;
    nombre=new String[8];
    Boolean name=false;

    for(int n=0;n<nombre.length;n++){

        while(name.equals(false)){
            System.out.println("Ingresar un nombre:");
            nombre[n]=key.next();
            if(nombre[n].equals(Nombres.values())){
                name=true;
        }else{
                System.out.println("Nombre invalido");
            }

        }
    }

}
plush geyserBOT
#

<@&987246399047479336> please have a look, thanks.

honest dawn
#

I see you're a beginner. There's a simpler way to do this, but if you want you can use loop (other method is Set/Map or Enum#valueOf(String))
First think what you need to edit is

for should be in while

honest dawn
dawn current
#

and also don't use Boolean, use boolean

#

and use while(name) instead of while(name.equals(false))

#
       String[] nombre;
        nombre=new String[8];

you can do it in one line String[] nombre = new String[8]

#

Follow conventions for names

#

so Nombrar should be lowercase

#

and Ejercicio_1 shouldn't have a _

#

also name is misleading, why a name would be a boolean, rename this variable to a better name

#

and I advise you to use english, it's easier for everyone, and you are currently doing all english so you are not even trying to use spanish for all

#

And to answer your question

#

there are two ways

#
  • either you use Nombres.valueOf and catch the exception
  • or you do a loop over Nombres.values()
#

@spark knoll

spark knoll