变量超出范围?

时间:2019-10-14 21:41:01

标签: java

这是我老师的作业。不过,我在这一部分上仍然处于困境。它说超出范围,但我返回了变量。

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);
}

我希望它可以打印年份,但是由于某种原因它看不到变量。

2 个答案:

答案 0 :(得分:1)

您看到的问题是monthborn是在一个位置定义的,即monthConvert()方法,而您正试图在另一地方使用它,即main()方法。

在您的main()方法中,您根本没有调用monthConvert(),因此,即使该方法返回值,也不会调用该方法。

您可以执行以下操作来调用方法并将结果保存到变量中:

String s = monthConvert(2);

请注意,上面将值保存在名为s的变量中以突出显示monthConvert()中的变量名与存储结果的变量名无关。

答案 1 :(得分:0)

正如人们评论的那样,变量monthborn仅存在于您的monthConvert()方法中,而不存在于main()方法中。我修改了您的代码,并在下面显示,以演示如何调用方法以获取monthborn变量。

注意:我删除了dayyear变量,因为它们尚未声明。还

有问题的行是:

String month = monthConvert(1);

它设置一个新的month变量,它等于字符串"January",因为它是给定参数1时方法返回的字符串


public static void main(String[] args) {
    String month = monthConvert(1);
    System.out.println("You were born on " + 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;
}