猿问

创建一个返回字符串数组的方法

我正在努力学习Java的艰辛方式,挥舞着头脑,理解如何以困难的方式做事。因此,这可能是不可能的,但是,是否有可能使方法返回String类型的2D数组呢?


具体来说,这是一种提示用户输入二维数组中的名字和姓氏列表的方法。


public static String nameTest() {

    String nameList[][] = new String[publicArraySize][publicArraySize];


            //get user names here


    return nameList;  <--gives error can't convert from String[][] to String

    }

同样,这是为了获取2D数组中的名称列表。然后,步骤2是在方法中返回该字符串数组。


感谢您的时间。


Smart猫小萌
浏览 226回答 3
3回答

跃然一笑

是的,可以,但是在您的代码中,您也需要使方法签名为String [] [](提供更多代码以检查其他行是否错误)。在旁边,您可以创建一个新的对象“名称”,并填充诸如FirstName和LastName之类的字段,然后在每次提供时将它们添加到ArraList中。

米脂

首先,我要说的是,函数定义的基本规则是函数的类型应该与返回值的类型相同。这意味着如果您将函数定义为public static String nameTest(){}您的返回值应为String。要解决此错误,您需要将功能更改为public static String[][] nameTest() {&nbsp; &nbsp; String nameList[][] = new String[publicArraySize][publicArraySize];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //get user names here&nbsp; &nbsp; return nameList;&nbsp; <--gives error can't convert from String[][] to String&nbsp; &nbsp; }

SMILET

这行:public static String nameTest()是方法签名。这就像一份合同,您必须遵守此合同。public&nbsp;->这意味着可以从任何类调用该方法。static&nbsp;->这意味着该方法是静态的。String->这意味着该方法将返回String类型的对象。问题是您正尝试返回一个二维String数组。()->这意味着该方法没有参数。因此,您不能使用参数调用此方法。为了解决您的问题,您必须通过以下方式将返回类型从String更改为String [] []:public static String[][] nameTest() {&nbsp; &nbsp; String nameList[][] = new String[publicArraySize][publicArraySize];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //get user names here&nbsp; &nbsp; return nameList;}
随时随地看视频慕课网APP

相关分类

Java
我要回答