将String扫描器转换为类类型

时间:2015-06-09 13:44:07

标签: java string types

我是Java中的一个前任者,我有一个关于将String转换为Class类型(?)的问题。

我的主要课程有:

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();

但我必须将最后String转换为枚举类型:

public enum EmployeeType {
    A, 
    B, 
    C
}

任何提示?

2 个答案:

答案 0 :(得分:1)

你可以这样做:

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

答案 1 :(得分:0)

您可以使用switch直到Java7 ...

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

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

或者您可以与if

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