【问题标题】:How come I cannot return the value of my array?为什么我不能返回我的数组的值?
【发布时间】:2012-10-04 10:05:47
【问题描述】:

我对 Java 很陌生,所以可能对此有一个简单的解释,但无论如何我可能会觉得很愚蠢。

我正在尝试使用一种方法来读取文件,从该文件数据中填充一个二维数组,然后返回填充的数组,以便我可以在我的主类中使用它并从那里打印出数组内容。

这是我目前得到的:

public class ScoreProcessor { 
    static public readFile() throws IOException {
        File filedata = new File("src/JavaApp2/Data.txt");        
        Scanner file = new Scanner (filedata);        
        int row = 0, col = 0;            
        String[][] scores = new String[8][5];

        while (file.hasNextInt()){               
            Scanner readfile = new Scanner (filedata);
            readfile.nextLine();
            readfile.useDelimiter(",");

            while (readfile.hasNext(",")){
                String line = readfile.next();
                scores[row][col] = line; 
                col++;  
            }            
            row++;  
            col=0;
        }
        return scores;
    }    
}

任何帮助将不胜感激,谢谢。

【问题讨论】:

  • 您需要将readFile 作为返回类型String[][] 我也会使用您的IDE 来修复您的格式。

标签: java arrays methods


【解决方案1】:

正如 Peter Lawrey 所说,您需要将 rtuerntype String[][] 添加到您的方法头中,如下所示:

static public String[][] readFile() throws IOException {
   ...

此外,如果您事先不知道大小,则不应使用数组。在这种情况下使用列表。

【讨论】:

    【解决方案2】:
    static public String[][] readFile() throws IOException {
    

    【讨论】:

      【解决方案3】:

      关于返回声明你的返回类型在方法中。

       public static String[][] readFile() throws IOException {
      

      关于你可以使用的打印

      Arrays.deepToString(scores);
      

      【讨论】:

        猜你喜欢
        • 2014-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-06
        • 1970-01-01
        • 2014-12-11
        • 1970-01-01
        • 2011-04-13
        相关资源
        最近更新 更多