如何将用户输入字符串设置为ENUM Java

时间:2018-12-09 21:04:44

标签: java string input enums

因此,我希望用户输入用户输入的字符串并将其存储到ENUM中,但是我不确定如何将新字符串存储在ENUM中。

public enum Food {
  PIZZA("", "", ""),

private final String location;
private final String calories;
private final String fat;

Food(String location, String calories, String fat){
    this.location = location;
    this.calories= calories;
    this.fat= fat;
}
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

String location = input.nextLine();
String calories= input.nextLine();
String fat= input.nextLine();

Food(location, calories, fat);

我不认为食物(位置,卡路里,脂肪);在枚举中设置输入,我可以使用什么来设置它?

1 个答案:

答案 0 :(得分:0)

不确定要执行的操作是什么,但是可以从枚举字段中删除final修饰符,添加getter和setter并在用户输入数据后将其存储。例如:

public enum Food {
    PIZZA;

    private String location;
    private String calories;
    private String fat;

    public String getLocation() { return location; }
    public void setLocation(String location) { this.location = location; }

    public String getCalories() { return calories; }
    public void setCalories(String calories) { this.calories = calories; }

    public String getFat() { return fat; }
    public void setFat(String fat) { this.fat = fat; }


    @Override
    public String toString() {
        return String.format("%s: %s %s %s", super.toString(), location, calories, fat);
    }
}

主要

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    Food.PIZZA.setLocation(input.nextLine());
    Food.PIZZA.setCalories(input.nextLine());
    Food.PIZZA.setFat(input.nextLine());

    System.out.println(Food.PIZZA);
}

输出

locat
calor
fat
PIZZA: locat calor fat