【问题标题】:Array inside array not working as intended数组内的数组未按预期工作
【发布时间】:2018-05-03 14:07:16
【问题描述】:

我有一个包含行的文本文件,其中的单词用逗号分隔。我正在尝试在另一个数组中创建一个数组,以便我可以从文本文件中调用特定的单词。现在我可以将文本文件的每一行保存到一个数组中,但我不知道如何调用一行中的特定单词。

文本文件

Hat, dog, cat, mouse
Cow, animal, small, big, heavy
Right, left, up, down ,behind
Bike, soccer, football, tennis, table-tennis

代码

animals = new Scanner(new File("appendixA.txt"));
// code for number of lines start
File file =new File("appendixA.txt");

if(file.exists()) {

    FileReader fr = new FileReader(file);
    LineNumberReader lnr = new LineNumberReader(fr);

    int linenumber = 0;

    while (lnr.readLine() != null) {
        linenumber++;
    }

    lnr.close();

    // code for number of lines end

    String animal[] = new String[linenumber];

    for (int i = 0; i < linenumber; i++) {
        String line = animals.nextLine();
        animal[i] = line;

        for (int j = 0; j < animal[i].split(",").length; j++) {
            String animalzzz[] = animal[i].split(",");


        }


    }
}

【问题讨论】:

  • 你想保留逗号还是只想要数组中的单词?
  • 你在哪里使用多维数组?什么是/不工作?你debug your program了吗? --- 关于 oyur 代码的一些说明:请修正你的缩进和代码风格 --- String animal[] - 你应该在类型之后写数组括号,而不是在变量名之后,因为它们会影响类型:String[] animal - -- 空行数量较多,请少用。目前,空行并不能提高可读性。
  • @GBlodgett 我不想要逗号,我知道我可以使用 .split() 函数,但我不知道从那里去哪里
  • LineNumberReader 在您想计算文件中的所有行时没用。仅当您在读取文件时对行数感兴趣时才有用

标签: java arrays string arraylist text


【解决方案1】:

您需要使用二维数组。二维数组用于表示表结构。在您的情况下,您有多行,每行都有多个值。因此,一个数组将用于表示一行,另一个数组将用于表示每一行中的列值。

        String[][] animal = new String [linenumber][];

        for (int i = 0; i < linenumber; i++) {
                String line = animals.nextLine();
                String[] oneRowAnimals = line.split(",").trim();
                for(int j=0; j<oneRowAnimals.length; j++) {

                    // Here you are storing animals
                    animal[i][j] = oneRowAnimals[j];
                }
        }
        // Now you can access them by index.
        // For exmaple, this would give you "dog"
        String animalName = animal[0][1]; 

【讨论】:

  • 更多解释,尤其是 wrt。多维和参差不齐的数组,将是有益的。请不要写String animal[][]
  • 我收到错误:无法在数组类型 String[] 上调用 split(String)
  • @htmlnoob 更新了答案,请检查。 Turing85 根据建议更改了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-05
  • 1970-01-01
  • 1970-01-01
  • 2018-08-03
  • 1970-01-01
  • 2018-08-20
相关资源
最近更新 更多