所以我已经坐在这里过去5个小时,试图了解我在做什么,我有一个简单的初学者任务,即创建多种不同的方法来找出存储为全局名称的用户名。变量,以及它们出生的月份以整数形式存储。一旦存储了整数,我就使用switch语句来对应某个月份,我认为到目前为止该月份还不错。但是,在我的主类中调用方法时,我始终为UsersName变量和monthString变量返回空值。
public class BirthMonthWithFunctions {
public static String UsersName;
public static void main(String[] args) {
String monthString = null;
BirthMonthWithFunctions bm = new BirthMonthWithFunctions();
BirthMonthWithFunctions.getUsersName();
bm.getUsersBirthMonthNumber();
BirthMonthWithFunctions.computeBirthMonth(0);
System.out.print(UsersName + "Was born in: " + monthString);
}
static void getUsersName() {
String UsersName = JOptionPane.showInputDialog(null, "What is your name?");
}
public int getUsersBirthMonthNumber() {
int BirthMonth = Integer.parseInt(JOptionPane.showInputDialog(null,"Which month were you born in as an integer between 1-12?"));
return BirthMonth;
}
public static String computeBirthMonth(int BirthMonth) {
int choice = BirthMonth;
String monthString;
switch(choice) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid Month";
break;
}
return monthString;
}
}
答案 0 :(得分:0)
请您尝试一下我编辑的这段代码。
public static void main(String[] args) {
String monthString = null;
BirthMonthWithFunctions bm = new BirthMonthWithFunctions();
BirthMonthWithFunctions.getUsersName();
int BirthMonth = bm.getUsersBirthMonthNumber();
BirthMonthWithFunctions.computeBirthMonth(BirthMonth);
System.out.print(UsersName + "Was born in: " + monthString);
}
static void getUsersName() {
UsersName = JOptionPane.showInputDialog(null, "What is your name?");
}
还从以下方法中删除String变量声明:computeBirthMonth
应该是这样的:
public static String computeBirthMonth(int BirthMonth) {
int choice = BirthMonth;
switch(choice) {..............
}
return monthString;
}