我需要返回用户从命令行输入的数字的值。
例如:
java Test 5
1 =一月
2 =二月,等等...
我尝试使用switch语句,但是,我收到输出:
May
5
当从命令行输入时。我不确定为什么会这样。
输出应为:
/May
这是到目前为止我尝试过的:
class theDate {
private int month;
public theDate(int theMonth){
month = theMonth;
}
public theDate(){
}
public int getMonth() {
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
}
return month;
}
public String getDate(String[] datePartsObj) {
month = Integer.parseInt(datePartsObj[0]);
return "/" + month;
}
}
public class Test {
private MyDate myDateObj;
public Test(){
}
public static void main(String [] args) {
String[] datePartsObj;
datePartsObj = args[0].split("/");
int month = Integer.parseInt(datePartsObj[0]);
theDate myDateObj = new theDate(month);
System.out.println(myDateObj.getMonth());
}
}
我对Java还是很陌生,因此不胜感激!
好像您想通过检查给定的数字来返回月份名称。
您必须更改返回String
而不是int
的方法,然后可以直接在匹配的case
中返回名称,如下所示:
public String getMonth() {
switch (month) {
case 1:
// print the name of the month
System.out.println("January");
// and return it... same for ever other month
return "January";
case 2:
System.out.println("February");
return "February";
case 3:
System.out.println("March");
return "March";
case 4:
System.out.println("April");
return "April";
case 5:
System.out.println("May");
return "May";
case 6:
System.out.println("June");
return "June";
case 7:
System.out.println("July");
return "July";
case 8:
System.out.println("August");
return "August";
case 9:
System.out.println("September");
return "September";
case 10:
System.out.println("October");
return "October";
case 11:
System.out.println("November");
return "November";
case 12:
System.out.println("December");
return "December";
// for any number less than 1 and greater than 12 throw an exception
default:
throw new RuntimeException("Invalid month number");
}
}
您的整个工作流程都有2条打印语句要执行。一种在getMonth()
方法内(正在打印“ MAY”),另一种在main()
方法内(正在打印5)
您需要做的是将getMonth()
的返回类型从int
更改为String
public String getMonth() {
switch (month) {
case 1: return "January";
case 2: return "February";
case 3: return "March";
case 4: return "April";
case 5: return "May";
case 6: return "June";
case 7: return "July";
case 8: return "August";
case 9: return "September";
case 10: return "October";
case 11: return "November";
case 12: return "December";
}
return "Invalid Month";
}
这样,您的工作流程将在main方法中只有一个打印语句。