我将如何使用.split函数将不同的数据类型分为2D数组?

我有一个.txt文件,其中包含如下几行:

Robot 1923 human M 12M Star Gaze,73,1543,B,Joseph Smith

Sanction 1932 indigo X 23X GI,9999,14,R

我有多个2D数组,每种数据类型一个。整数,字符,字符串和双精度。每个数组仅需要填充其特定的数据类型。我相信我应该使用.split函数来执行此操作,但是我不知道如何执行。谢谢您的帮助,在此先感谢您,如果我不太清楚,我可以尝试在答复中帮助您解决问题。

zucker19782002 回答:我将如何使用.split函数将不同的数据类型分为2D数组?

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];

请记住,此代码对解决输入质量没有多大作用。您的输入文件应该是常规文件(每行中的列数相同,整个列中的数据类型相同),否则代码将严重失败。

本文链接:https://www.f2er.com/2959412.html

大家都在问