我有一个小任务要完成,要求用户输入月份或等值的数字,它会返回输入月份的数值,或与输入数值对应的月份。约束如下: - 它不能包含任何类型的 GUI - 我必须使用 BufferedReader 进行输入 - 我必须使用至少一个 Switch 语句
如果有人有任何想法,将不胜感激。到目前为止,我的代码如下:
/**
* Month task
*
* @author Dan Foad
* @version 0.01
*/
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Months {
public static void main(String []args) throws IOException {
int iInput;
boolean isParseable;
String szInput;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please type either the number of the month, or the month itself to convert.");
System.out.print("> ");
szInput = br.readLine();
try {
Integer.valueOf(szInput);
isParseable = true;
}
catch(Exception e) {
isParseable = false;
}
if (isParseable) {
iInput = Integer.valueOf(szInput);
System.out.println(numberToMonth(iInput));
}
else {
szInput = szInput.toLowerCase();
System.out.println(monthToNumber(szInput));
}
return;
}
public static String numberToMonth(int iMonth) {
String MonthReturn;
switch(iMonth) {
case (1): MonthReturn = "January"; break;
case (2): MonthReturn = "February"; break;
case (3): MonthReturn = "March"; break;
case (4): MonthReturn = "April"; break;
case (5): MonthReturn = "May"; break;
case (6): MonthReturn = "June"; break;
case (7): MonthReturn = "July"; break;
case (8): MonthReturn = "August"; break;
case (9): MonthReturn = "September"; break;
case (10): MonthReturn = "October"; break;
case (11): MonthReturn = "November"; break;
case (12): MonthReturn = "December"; break;
default: MonthReturn = "0"; break;
}
return MonthReturn;
}
public static int monthToNumber(String szMonth) {
int MonthReturn;
switch(szMonth) {
case ("january"): MonthReturn = 1; break;
case ("february"): MonthReturn = 2; break;
case ("march"): MonthReturn = 3; break;
case ("april"): MonthReturn = 4; break;
case ("may"): MonthReturn = 5; break;
case ("june"): MonthReturn = 6; break;
case ("july"): MonthReturn = 7; break;
case ("august"): MonthReturn = 8; break;
case ("september"): MonthReturn = 9; break;
case ("october"): MonthReturn = 10; break;
case ("november"): MonthReturn = 11; break;
case ("december"): MonthReturn = 12; break;
default: MonthReturn = 0; break;
}
return MonthReturn;
}
}