[英]Java Weekday input Validation
有没有一种“简洁的”方式来编写此代码? 我追求简单,这对我来说似乎有点重复。 (如果有人想知道的话,我将日期更改为数字,以便可以在自己的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();
}
import java.io.*;
import java.text.*;
import java.util.*;
public class DayofWeekExample {
public static int getIntDayOfWeek(String dayOfWeek)
{
try
{
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("EEE");
date = (Date)formatter.parse(dayOfWeek);
GregorianCalendar g = new GregorianCalendar();
g.setTime(date);
return g.get(Calendar.DAY_OF_WEEK);
}
catch (ParseException e)
{
System.out.println("Exception :"+e);
}
return 0;
}
public static void main(String[] args) throws IOException {
// Beginnig day is Sunday
Scanner scanText = new Scanner(System.in);
System.out.print("Enter Day: ");
String weekday = scanText.nextLine();
System.out.println("-> " + getIntDayOfWeek(weekday));
}
}
一周的第一天是从当前语言环境派生的。 如果您未设置日历的区域设置( Calendar.getInstance(Locale)或new GregorianCalendar(Locale) ),它将使用系统的默认设置。
因为您基本上是将String
值映射为int
值,所以我认为这是Map
的典型用例。 您可以像下面这样编写(一个缺点是必须初始化Map
但是可以对其进行封装以提高可读性)
Scanner scanText = new Scanner(System.in);
System.out.print("Enter Day: ");
String weekday = scanText.nextLine();
int day = 0;
Map<String,Integer> day_of_week=new HashMap<String,Integer>();
day_of_week.put("MONDAY", 1);
day_of_week.put("TUESDAY", 2);
day_of_week.put("WEDNESDAY", 3);
day_of_week.put("THURSDAY", 4);
day_of_week.put("FRIDAY", 5);
day_of_week.put("SATURDAY", 6);
day_of_week.put("SUNDAY", 7);
if(day_of_week.containsKey(weekday.toUpperCase())){
day = day_of_week.get(weekday.toUpperCase()).intValue();
}else{
System.out.print("Error! Invalid day: ");
weekday = scanText.nextLine();
}
我敢肯定,在从else
块读取值之后,您一定想过要再次进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.