我有一个程序,它将从文件中读取并将文件的每一行添加为数组的元素。我现在想做的是弄清楚如何编辑数组中的某些项目。
问题是我的输入文件看起来像这样
number of array items
id, artist name, date, location
id, artist name, date, location
例如
2
34, jon smith, 1990, Seattle
21, jane doe, 1945, Tampa
因此,如果我调用 artArray[0]
我会得到 34, jon smith, 1990, Seattle
但我正在尝试弄清楚如何更新 Seattle
当输入 34
的 id 时,是否可以用逗号分隔数组中的每个元素?或者使用多维数组代替?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ArtworkManagement {
/**
* @param args
*/
public static void main(String[] args) {
String arraySize;
try {
String filename = "artwork.txt";
File file = new File(filename);
Scanner sc = new Scanner(file);
// gets the size of the array from the first line of the file, removes white space.
arraySize = sc.nextLine().trim();
int size = Integer.parseInt(arraySize); // converts String to Integer.
Object[] artArray = new Object[size]; // creates an array with the size set from the input file.
System.out.println("first line: " + size);
for (int i = 0; i < artArray.length; i++) {
String line = sc.nextLine().trim();
// line.split(",");
artArray[i] = line;
}
System.out.println(artArray[0]);
sc.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
最佳答案
你就快到了,但是split返回一个数组,因此您需要一个数组的数组。
您可以更改此行
Object[] artArray = new Object[size];
通过这个,您还可以使用 String
而不是 Object
,因为这确实是一个字符串。
String[][] artArray = new Object[size][];
然后你可以将数组添加到数组的数组中
artArray[i] = line.split();
最后使用两个索引访问它:
artArray[indexOfTheArray][indexOfTheWord]
此外,如果您想打印数组,请使用:
System.out.println(Arrays.toString(artArray[0]));
关于java数组: split elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49306939/