简体   繁体   English

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

[英]How to set user input Strings into ENUM Java

So I want the user to input user input strings and store them into an ENUM but I'm not sure how to store the new strings in the ENUM. 因此,我希望用户输入用户输入的字符串并将其存储到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);

I don't think the Food(location, calories, fat); 我不认为食物(位置,卡路里,脂肪); sets the input in the enum, what could I use in order to set it? 在枚举中设置输入,我可以使用什么来进行设置?

Not sure what you're trying to achieve by doing this, but you can drop final modifier from the enum fields, add getters and setters and store them once user input data. 不确定要执行的操作是什么,但是您可以从枚举字段中删除final修饰符,添加getter和setter并在用户输入数据后存储它们。 Eg: 例如:

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

Main 主要

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

Output 输出量

locat
calor
fat
PIZZA: locat calor fat

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

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