gpt4 book ai didi

Java 工作日输入验证

转载 作者:行者123 更新时间:2023-12-02 03:31:00 26 4
gpt4 key购买 nike

是否有一种“更整洁”的方式来编写这段代码?我是一个追求简单的人,这对我来说似乎有点重复。 (我将天数更改为数字,以便我可以在自己的 if 语句中使用它们,如果有人想知道的话)有什么建议吗?

Scanner scanText = new Scanner(System.in);

System.out.print("Enter Day: ");
String weekday = scanText.nextLine();

int day = 0;

if (weekday.equalsIgnorCase("Monday"))
day = 1;
else if (weekday.equalsIgnorCase("Tuesday"))
day = 2;
else if (weekday.equalsIgnorCase("Wednesday"))
day = 3;
else if (weekday.equalsIgnorCase("Thursday"))
day = 4;
else if (weekday.equalsIgnorCase("Friday"))
day = 5;
else if (weekday.equalsIgnorCase("Saturday"))
day = 6;
else if (weekday.equalsIgnorCase("Sunday"))
day = 7;
else {
System.out.print("Error! Invalid day: ");
weekday = scanText.nextLine();
}

最佳答案

如果您没有使用 JDK 1.8,以下代码可能会对您有所帮助:

     List<String> strDays = Arrays.asList("Monday", "Tuesday", "Wednesday", "Thusday", "Friday", "Saturday", "Sunday" );

String weekday = scanText.nextLine();

int day = 0;
if(strDays.contains(weekday)) {

day = strDays.indexOf(weekday) + 1;
} else {
System.out.print("Error! Invalid day: ");
weekday = scanText.nextLine();
}

关于Java 工作日输入验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38095338/

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