Convert String scanner to class type

87 views Asked by At

I'm a begginner in Java and I have a question about convert String to a Class Type (?).

My main class have this:

Scanner scanner = new Scanner(System.in);
    System.out.println("Inserir 1o nome:");
    String firstname = scanner.next();
    System.out.println("Inserir apelido:");
    String lastname = scanner.next();
    System.out.println("Inserir género:");
    String gender = scanner.next();
    System.out.println("Inserir tipo de funcionário (A, B ou C):");
    String type = scanner.next();

But I have to convert last String to an enum type:

public enum EmployeeType {
    A, 
    B, 
    C
}

Any hint?

2

There are 2 answers

0
couettos On BEST ANSWER

You can do :

String type = scanner.next();
EmployeeType enumType = EmployeeType.valueOf(type);
0
Jordi Castilla On

You can use switch up to Java7...

String type = scanner.next();
EmployeeType eType = EmployeeType.valueOf(type);

switch(eType) {
    case A:
       // do what you need
       break;
    case B:
    // etc...
}

Or you can compare with an if

if (type.equals(EmployeeType.A.toString()) {
    // do your stuff
} else if (type.equals(EmployeeType.B.toString()) {
    // etc...
}