作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我希望用户输入 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/
我是一名优秀的程序员,十分优秀!