有没有一种“整齐的”方式编写此代码?我追求简单,这对我来说似乎有点重复。 (如果有人想知道的话,我将把日期更改为数字,以便可以在自己的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 - Java Weekday输入验证,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38095338/

10-12 21:46