0

嗨,我正在编写一种方法来提示用户输入一些值。我想存储这些值并将一个数组返回给程序。这是我写的代码

public static int[] readInQuarters(String[] firstName, String[] lastName)
{//method to read in quarters
    int[] quarter1= new int[firstName.length];
    int[] quarter2= new int[firstName.length];
    int[] quarter3= new int[firstName.length];
    int[] quarter4= new int[firstName.length];

    Scanner input=new Scanner(System.in);
    for(int i=0;i<firstName.length;i++){
        System.out.printf("Enter the 1st quarter figure(to the nearest million) for %s %s :",firstName[i], lastName[i]);
        quarter1[i]= input.nextInt();
    }
    for(int i=0;i<firstName.length;i++){
        System.out.printf("Enter the 1st quarter figure(to the nearest million) for %s %s :",firstName[i], lastName[i]);
        quarter1[i]= input.nextInt();
    }
    for(int i=0;i<firstName.length;i++){
        System.out.printf("Enter the 2nd quarter figure(to the nearest million) for %s %s :",firstName[i], lastName[i]);
        quarter2[i]= input.nextInt();
    }
    for(int i=0;i<firstName.length;i++){
        System.out.printf("Enter the 3rd quarter figure(to the nearest million) for %s %s :",firstName[i], lastName[i]);
        quarter3[i]= input.nextInt();
    }
    for(int i=0;i<firstName.length;i++){
        System.out.printf("Enter the 4th quarter figure(to the nearest million) for %s %s :",firstName[i], lastName[i]);
        quarter4[i]= input.nextInt();
    }

    return quarter1;
    return quarter2;
    return quarter3;
    return quarter4;
}

出现 return 季度 1 和其他是无法访问的语句错误。我很困惑为什么?

4

5 回答 5

0

That's because the control switches back to the calling method right after the first return statement

return quarter1; // only this is effective
return quarter2; // these are never reached
return quarter3;
return quarter4;

Try this

int[] arr = new int[4];
arr[0] = quarter1;
arr[1] = quarter2;
arr[2] = quarter3;
arr[3] = quarter4;
return arr;
于 2013-11-13T12:51:56.323 回答
0

您只能使用一个 return 语句返回一个值。一旦你使用return,该方法就退出了,不会再有任何东西了。

如果您希望返回多个值,请考虑改用数组。

于 2013-11-13T12:50:35.190 回答
0

return quarter1将停止方法并返回值。

如果需要返回多个值,可以创建一个类来保存所有值

或者

如果所有值都属于同一类型,则可以使用 anArray或 a Collection

于 2013-11-13T12:50:41.917 回答
0

您只能编写一个返回语句,并且返回语句应该是方法的最后一行。因此,当您编写时return quarter1;,此行之后的所有语句都将无法访问

查看这个oracle 文档以获取有关从方法返回值的更多信息

于 2013-11-13T12:49:15.293 回答
0

一个方法只会运行一个return语句;一旦运行,其他的将被忽略。如果要返回四个项目,则必须将它们放入某种容器对象中,例如int[]. 这可能看起来像这样:

return new int[][]{quarter1, quarter2, quarter3, quarter4};
于 2013-11-13T12:49:52.653 回答