简体   繁体   中英

String split gives array out of bounds

I am required to split a string which has been read from a external file. I have managed to split the string using this code;

String[] parts = line.split("\\.");
String part1 = parts[0];
String part2 = parts[1];

Now when I attempt to access the data, part1 at index[0] works fine, however trying to get index [1] throw an index out of bounds exception. The data I'm trying to split looks like so

886.0452586206898 27115740907.871643
888.0387931034484 26218442896.246094
890.032327586207 25301777157.154663
892.0258620689656 24365534070.686035
894.0193965517242 23409502709.11487

Am I meant to remove white space before doing the string split?

I guess you are reading the file line by line, then you should split first against a "space" and then again the dot, otherwise you will get corrupted data...

886.0452586206898 27115740907.871643

as you can see, there are 2 elements in each line that can be split by dot

Since i highly doubt that the index is getting lost. You might want to try this code to find out if the data is completly valid. If the error still occurs you might have the cause of the error at some different place, and want to show your actuall stacktrace.

while ((line = br.readLine()) != null) { 
    if(line.contains(".")) {
        String[] parts = line.split("\\."); 
        String part1 = parts[0]; 
        String part2 = parts[1];
    } else {
        System.out.println("Corrupted data as: " + line);
    }
}
    String[] parts = null;
    String part1 = null;
    String part2 = null;


    System.out.println(parts[2]);
    while ((line = br.readLine()) != null) {
        System.out.println(line);
        parts = line.split("\\.");
        part1 = parts[0];
        part2 = parts[1];
    }

It is not working because you are trying to reach a variable that you declarated inside the while. Try to declarate outside it.

Do you want to extract each number from the input, then split on the decimal? In that case, use Scanner to read in each number first, then split:

Scanner s = new Scanner(System.in);
while (s.hasNext()) {
  String num = s.next();
  String[] parts = num.split("\\.");
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM