【问题标题】:Multi-Dimensional array in Linked List not working?链表中的多维数组不起作用?
【发布时间】:2016-11-26 05:43:01
【问题描述】:

所以我有这个代码:

    public static void main (String[] args) throws IOException
{
    Queue popcorn = new LinkedList();
    BufferedReader in = null;
    int j = 0;
    try {
        File file2 = new File("Events.txt");
        in = new BufferedReader(new FileReader(file2));

        String str;
        String [][] process = new String[][];
        while ((str = in.readLine()) != null) {
            String[] arr = str.split(" ");
            for(int i=0 ; i<str.length() ; i++){
            process[j][i] = in.readLine();
        }
            j++;
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

} 

它不起作用。它抛出“变量必须提供维度表达式或数组 初始化器”

我正在尝试在此网页回答“http://www.chegg.com/homework-help/questions-and-answers/hired-biggy-s-popcorn-handle-popcorn-orders-store-write-java-console-application-reads-dat-q7220573”之后对其进行建模 我很确定这是行不通的。无论如何,这个链接列表似乎没有奏效。就我的 String[][] 进程声明而言,有人能指出我正确的方向吗?

【问题讨论】:

  • new String[][] - 不可能 创建 没有维度的数组,这就是消息所说的。这与变量声明是分开的。搜索一般提示/方向的错误消息。
  • 您需要提供数组大小。阅读java67.com/2014/10/…

标签: java arrays file


【解决方案1】:

你不能只初始化一个没有维度参数的数组。例如,这是无效的:

int[] array = new int[];

需要这样初始化:

int[] array = new int[10];

或者简单地说:

int[] array;
// ... //
array = new int[10];

多维数组也是如此。要创建一个包含 3 个大小为 5 的数组的数组,您可以输入:

int[][] array = new int[3][5];

但是,对于二维数组,您也可以放置:

int[][] array = new int[3][];
array[0] = new int[5];
array[1] = new int[7];
// ... //

关键是,您需要定义基本数组中有多少其他数组,并且还可以选择定义所有数组的大小或稍后简单地添加它们。在这种情况下,您需要更改

String [][] process = new String[][];

类似

String [][] process = new String[x][y];

【讨论】:

  • 好的!所以我将使用 String [][] process = new String[15][];不是吗?
  • 是的,但请记住,如果要使用行 process[j][i] = in.readLine(); ,则需要使用其他数组填充基本数组,这可以通过设置 process[j] = arr; 来完成。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-06
  • 2013-03-24
  • 2021-03-16
相关资源
最近更新 更多