簡體   English   中英

如何將用戶輸入字符串設置為ENUM Java

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

因此,我希望用戶輸入用戶輸入的字符串並將其存儲到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);

我不認為食物(位置,卡路里,脂肪); 在枚舉中設置輸入,我可以使用什么來進行設置?

不確定要執行的操作是什么,但是您可以從枚舉字段中刪除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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM