is there a "tidier" way of writing this code? I'm a stickler for simplicity and this seems a bit too repetitive for me. (I'm changing the days to numbers so that I can use them in their own if statements, if anyone was wondering) Any suggestions?
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();
}
If you are not using JDK 1.8, this code may help you:
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();
}