Java 变量超出范围?
这是我老师布置的家庭作业。不过,我在这一部分被卡住了。它说它超出范围,但我返回变量Java 变量超出范围?,java,Java,这是我老师布置的家庭作业。不过,我在这一部分被卡住了。它说它超出范围,但我返回变量 public static String monthConvert(int month) { String monthborn; if (month == 12) { monthborn = "December"; } else if (month == 11) { monthborn = "November"; } else if (month
public static String monthConvert(int month) {
String monthborn;
if (month == 12) {
monthborn = "December";
} else if (month == 11) {
monthborn = "November";
} else if (month == 10) {
monthborn = "October";
} else if (month == 9) {
monthborn = "September";
} else if (month == 8) {
monthborn = "August";
} else if (month == 7) {
monthborn = "July";
} else if (month == 6) {
monthborn = "June";
} else if (month == 5) {
monthborn = "May";
} else if (month == 4) {
monthborn = "April";
} else if (month == 3) {
monthborn = "March";
} else if (month == 2) {
monthborn = "Febuary";
} else if (month == 1) {
monthborn = "January";
}
return monthborn
}
public static void main(String[] args) {
System.out.println("You were born on " + monthborn + " " + day + " " + year);
}
我希望它能够打印年份,但出于某种原因,它没有看到变量。您看到的问题是,
monthborn
定义在一个地方,即monthConvert()
方法,而您正试图在另一个地方使用它,main()
方法
在main()
方法中,根本没有调用monthConvert()
,因此即使该方法返回值,也没有调用该方法
您可以执行以下操作来调用该方法并将结果保存在变量中:
String s = monthConvert(2);
请注意,上面将值保存在名为
s
的变量中,以突出显示monthConvert()
中的变量名与存储结果的变量名无关。正如人们评论的那样,变量monthborn
仅存在于monthConvert()中
方法,而不在main()方法中。我已经修改了您的代码,下面展示了如何调用方法来获取monthborn
变量
public static String monthConvert(int month) {
String monthborn;
if (month == 12) {
monthborn = "December";
} else if (month == 11) {
monthborn = "November";
} else if (month == 10) {
monthborn = "October";
} else if (month == 9) {
monthborn = "September";
} else if (month == 8) {
monthborn = "August";
} else if (month == 7) {
monthborn = "July";
} else if (month == 6) {
monthborn = "June";
} else if (month == 5) {
monthborn = "May";
} else if (month == 4) {
monthborn = "April";
} else if (month == 3) {
monthborn = "March";
} else if (month == 2) {
monthborn = "Febuary";
} else if (month == 1) {
monthborn = "January";
}
return monthborn
}
public static void main(String[] args) {
System.out.println("You were born on " + monthborn + " " + day + " " + year);
}
注意:我删除了day
和year
变量,因为它们尚未声明。然而
这条线是:
String month = monthConvert(1);
它将一个新的month
变量设置为字符串“一月”
,因为当给定参数1
变量存在于声明它们的作用域/块中。在这种情况下,仅在monthConvert()
方法内,而不在main()
方法内。您不返回变量,而是返回值。但是,在您的情况下,两者都不需要,因为您从未调用monthConvert()
。更不用说day
和year
从未声明过。它们来自哪里?缺少一个返回语句中的代码>。你也经常提到“变量”,但至少有一次陈述哪一个是“变量”!