I'm trying to parse a text file that looks like:
1 400.0 -1.6533271 5.7718643
2 401.0 -1.6596413 5.7751263
3 402.0 -1.6656540 5.7781345
4 403.0 -1.6713679 5.7808704
5 404.0 -1.6767864 5.7833152
So I've made the following method to get each of those values separately:
void parseFile(String filepath) throws FileNotFoundException, IOException {
FileReader filereader = new FileReader(filepath);
BufferedReader buffreader = new BufferedReader(filereader);
String s;
while ((s = buffreader.readLine()) != null) {
String[] tab = s.split(" ");
double number = parseDouble(tab[0]);
double lambda = parseDouble(tab[1]);
double re = parseDouble(tab[2]);
double im = parseDouble(tab[3]);
}
}
private double parseDouble(String s) {
if (s == null || s.isEmpty()) {
return 0.0;
} else {
return Double.parseDouble(s);
}
}
And when I'm trying to use lambda
value (to add it to my ArrayList
):
mylist.add(lambda);
I get an exception in line where lambda
is declared:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
What am I doing wrong?
答案 0 :(得分:0)
If you want to split a string by any whitespace, like space or tab, a better way to do it is:
myString.split("\\s+");
In your example, the whitespaces among columns could be spaces, tabs, or mixture of both. String[] tab = s.split(" ");
could results in only one element in variable tab
. In this case, when you try to access the second element, you will get OutOfIndex error cause there is only one element in tab.
答案 1 :(得分:0)
It might be because of formatting, but your data is separated by 5 spaces, you are splitting by 3 spaces. To avoid cases like that, it might make sense to use tabs or a regex like " {5}", stating the actual number of spaces instead of typing it manually.