gpt4 book ai didi

Java 开启枚举值

转载 作者:行者123 更新时间:2023-12-01 19:24:40 25 4
gpt4 key购买 nike

我希望用户输入 1 到 7 之间的数字。如果数字是 1,则打印出这是星期一。如果数字是 2,则打印出这是星期二,依此类推。

以下代码可以编译,但逻辑上不正确。

请参阅评论以了解需要帮助的地方:

import java.util.Scanner;

public class Test {
private enum Week {
MONDAY("1"), TUESDAY("2"), WEDNESDAY("3"),
THURSDAY("4"), FRIDAY("5"), SATURDAY("6"), SUNDAY("7");
private String value;

private Week(String value) {
this.value = value;
}
}

public static void main(String[] args) {

// How to instantiate this correctly, so that it doesn't only point to one value
Week week = Week.MONDAY;
System.out.print("Enter a number: ");
Scanner input = new Scanner(System.in);
String userInput = input.next();

// The switch parameter is not correct. This is what needs to be fixed.
// I want to use this case layout.
//The enums each have a value. The user enters a value. I want to switch over userInput.
switch (week) {
case MONDAY: System.out.println("That's Monday"); break;
case TUESDAY: System.out.println("That's Tuesday"); break;
case WEDNESDAY: System.out.println("That's Wednesday"); break;
case THURSDAY: System.out.println("That's Thursday"); break;
case FRIDAY: System.out.println("That's Friday"); break;
case SATURDAY: System.out.println("That's Saturday"); break;
case SUNDAY: System.out.println("That's Sunday"); break;
default: break;
}
}
}

最佳答案

在 Week 枚举中创建一个 get 方法,以便通过给定字符串获取 Week,例如:

public enum Week {
...
public Week getWeek(String key) {
... logic lookup
... obtain a Week(weekResult) with that key
return weekResult;
}
}

或者您可以尝试使用 Enum 方法 valueOf(...)。

我想,有了这个你就有必要开始了吧?

关于Java 开启枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53692697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com