我有一个包含行的文本文件,单词之间用逗号分隔。我正在尝试在另一个数组内创建一个数组,以便我可以从文本文件中调用特定的单词。现在我可以将文本文件的每一行保存到一个数组中,但我不知道如何调用一行中的特定单词。
文本文件
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(",");
}
}
}
最佳答案
您需要使用二维数组。二维数组用于表示表结构。在您的情况下,您有多行,每行都有多个值。因此,一个数组将用于表示一行,另一个数组将用于表示每行中的列值。
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];
关于java - 数组内的数组未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50157072/