变量是否超出范围?

问题描述 投票:-2回答:2

这是我老师的作业。不过,我在这一部分上被卡住了。它说超出范围,但我返回了变量。

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

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

java
2个回答
1
投票

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

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

您可以执行类似的操作来调用该方法并将结果保存在变量中:

String s = monthConvert(2);

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


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;
}
© www.soinside.com 2019 - 2024. All rights reserved.