我有一个 .txt 文件,其中有几行如下:
机器人 1923 人类 M 12M Star Gaze, 73, 1543, B, Joseph Smith
制裁 1932 靛蓝 X 23X GI,9999, 14, R
我有多个二维数组,每种数据类型一个。 Int、char、string 和 double。每个数组只需填充其特定的数据类型。我相信我应该使用 .split 函数来执行此操作,但我不知道如何执行。感谢任何帮助,提前致谢,如果我不够清楚,我可以尝试在回复中帮助澄清问题。
最佳答案
String.split() 上的 Java API 文档是一个很好的起点。
假设您知道如何从文件中获取String
(在示例代码中表示为line
),您可以执行以下操作:
String line = "C3PO 1977 humanoid M 11M Star Wars, 70, 1750, A, Anthony Daniels";
// As per the documentation, the split() method will return a String array, broken
// along the lines of the regular expression provided as argument
String[] values = line.split(",");
// Some variable names to hold the elements of the array
String foo;
int bar;
double baz;
String quz;
String actor;
foo = values[0];
// Converting data type... exceptions must be caught and handled
try {
bar = Integer.parseInt(values[1]);
}
catch(NumberFormatException e) {
e.printStackTrace();
}
catch(NullPointerException e1) {
e.printStackTrace();
}
try {
baz = Double.parseDouble(values[2]);
}
catch(NumberFormatException e) {
e.printStackTrace();
}
catch(NullPointerException e1) {
e.printStackTrace();
}
quz = values[3];
actor = values[4];
请记住,这段代码对于解决输入质量没有多大作用。您的输入文件应该是常规的(每行中的列数相同,整个列中的数据类型相同),否则代码将严重失败。
关于java - 如何使用 .split 函数将不同的数据类型分成二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59221980/