string - Java Weekday input Validation -
is there "tidier" way of writing code? i'm stickler simplicity , seems bit repetitive me. (i'm changing days numbers can use them in own if statements, if wondering) 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 not using jdk 1.8, code may 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(); }
Comments
Post a Comment