简体   繁体   English

在Java中将int转换为枚举

[英]converting int to enum in Java

I'm writing a polynomial calculator for a course assignment and I want to use enum in the switch case. 我正在为课程分配编写一个多项式计算器,并且我想在切换情况下使用枚举。

this is the enum method I wrote: 这是我写的枚举方法:

enum Options{
    ADDITION(1),
    MULTIPLICATION(2),
    EVALUATION(3),
    DERIVIATE(4),
    EXIT(5);

    public final int value;

     Options(int value){
         this.value = value;
     }

     public int getValue() {
         return value;
     }

     public static Options convert(int n) {
         for(Options o : values())
             if(o.getValue() == n)
                 return o;
         return null;
     }

}

this switch case in the program: 程序中的这种开关情况:

choice = mysc.nextInt();
Options o = Options.convert(choice);
switch(o)
{
    case ADDITION: Add(isRational);break;
    case MULTIPLICATION: Mul(isRational);break;
    case EVALUATION: Evaluate(isRational);break;
    case DERIVIATE: Derivative(isRational);break;
    case EXIT: break;
}

I want to use enum in the switch case but I want the input from the user to be an int, because it's a requirement for the assignment. 我想在开关的情况下使用枚举,但我希望用户的输入为int,因为这是分配的要求。

I want to convert the int I get from the user to the corresponding enum and use it in the switch case. 我想将我从用户那里得到的int转换为相应的枚举,并在switch的情况下使用它。

is there a way to convert it to the correct enum without using the convert method inside the enum? 有没有一种方法可以将其转换为正确的枚举,而无需使用枚举内部的convert方法?

Change your Enum to start at a 0 based index and use Enum.values()[index] . 更改Enum以从0开始的索引开始,并使用Enum.values()[index] Here is a simple example of the code and you'll probably want to introduce some sort of validation for invalid enum values: 这是一个简单的代码示例,您可能需要引入一些对无效枚举值的验证:

import java.io.BufferedInputStream;
import java.util.Scanner;

class Scratch {
    public static void main(String[] args) {
        Scanner input = new Scanner(new BufferedInputStream(System.in));
        System.out.println("Enter Value");
        int choice = Integer.parseInt(input.nextLine());
        System.out.println(choice);
        Options enumValue = Options.values()[choice];
        System.out.println(enumValue);
    }
}

enum Options{
    ADDITION(0),
    MULTIPLICATION(1),
    EVALUATION(2),
    DERIVIATE(3),
    EXIT(4);

    public final int value;

    Options(int value){
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

Output 输出量

在此处输入图片说明

Also FYI, Enum.values()[index] can be a bit expensive so keep that in mind if performance is an issue. 同样,仅供参考, Enum.values()[index]可能会有点昂贵,因此如果性能存在问题,请记住这一点。 As this is for an assignment, I doubt that is a concern but something to keep in mind for your own understanding. 因为这是一项任务,所以我怀疑这是一个问题,但您自己的理解需要牢记。

The mapping between integers and enum values is not really part of the API that uses the enum values. 整数和枚举值之间的映射实际上并不是使用枚举值的API的一部分。 Right now, you're asking the user to input an integer. 现在,您要让用户输入一个整数。 But what if you later write a GUI and present the names of the enum values in a drop down? 但是,如果您以后编写GUI并在下拉列表中显示枚举值的名称,该怎么办? Or write a parser to parse arithmetic expressions? 还是编写解析器来解析算术表达式? Those integers will no longer be relevant. 这些整数将不再相关。 They exist for the menu, so they belong to the part of the program that displays the menu. 它们存在于菜单中,因此它们属于显示菜单的程序部分。

You could introduce a Map<Integer,Options> that would map user input to enum values. 您可以引入Map<Integer,Options> ,它将用户输入映射到枚举值。 But if you added an new value to the enum, you'd have to remember to also add it to your Map . 但是,如果您向枚举添加了新值,则必须记住也将其添加到Map

I'd use the array returned by Options.values() . 我会使用由Options.values()返回的数组。 Iterate over it to display your menu, and use it to look up values by index. 遍历它以显示菜单,并使用它按索引查找值。 There are also caveats to this approach. 这种方法也有一些警告。 If you rearrange the values in your code, their order will change in the array as well. 如果您重新排列代码中的值,则它们的顺序也会在数组中更改。 The order of menu options would change, possibly confusing the user. 菜单选项的顺序将改变,可能会使用户感到困惑。 But your program would still run. 但是您的程序仍然可以运行。 The real problem with using enum ordinal values is when you serialize them (write them to persistent storage, like a file) and then try to read them back after changing the order. 使用枚举序数值的真正问题是将它们序列化(将它们写入文件等持久性存储),然后在更改顺序后尝试将其读回。 As long as you're not serializing your enum constants, it's okay to use their ordinal values. 只要您不序列化枚举常量,就可以使用它们的序数值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM