简体   繁体   English

子字符串-StringIndexOutOfBounds异常Java

[英]Substring - StringIndexOutOfBounds exception java

I've been working on a program to collect data from a file and do some stuff to it (as evident in the code and pseudocode) however I'm having difficulty getting each element of the string into the right array. 我一直在研究一个程序来从文件中收集数据并对它做一些事情(在代码和伪代码中很明显),但是我很难将字符串的每个元素放入正确的数组中。 A line from a file looks like this: 文件中的一行如下所示:

1980 Aug    945 100 Allen

I'm wanting to use the substring method because that'd be the easiest in my opinion. 我想使用substring方法,因为在我看来这将是最简单的方法。 Is there a better way of doing it? 有更好的方法吗? Here's my code thus far. 到目前为止,这是我的代码。 Where does the problem lie exactly, and how should I fix it? 问题到底在哪里,我该如何解决? Thanks! 谢谢! :) :)

import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.lang.String; 
public class Hurricanes2
{

public static void main(String [] args) throws IOException 
{
int counter = 0;
String [] token = new String[1000];

String [] tokenElements = new String[128];
String [] hurricaneYear = new String[64];
String [] hurricaneName = new String[64];
String [] hurricaneMonth = new String[64];
int []  hurricaneCategory = new int[64];
double [] hurricanePressure = new double[64];
double tempKnots;
double knotsToMph; 
double [] hurricaneWindSpeed = new double[64];
double categoryAverage;
double pressureAverage;
double speedAverage; 
String headerData = "                          Hurricanes 1980 - 2006\n\n Year         Hurricane       Category        Pressure(MB)        Wind Speed     (MPH)\n========================================================================";
Scanner in = new Scanner(System.in);
Scanner inFile = new Scanner(new File("hurcData2.txt"));
System.out.println(headerData);

/**---Use for-each (line:token) 
 * Parse for year - > year array
 * parse for name - > name array
 * parse for knots - > tempKnots
 * knotsToMph = tempKnots  * 1.15078
 * hurricaneWindSpeed[counter] = knotsToMph
 *  enter if-else to calculate category (hurricaneCategory [] = 1,2,3,4, or 5):
 *      74-95 cat1 
 *      96-110 cat2
 *      111 - 129 cat3
 *      130-156 cat4
 *      157 or higher cat 5
 * 
 * 
 */
 while(inFile.hasNextLine()){

        token[counter] = inFile.nextLine();
        String tempToken = token[counter]; 
        hurricaneYear[counter] = tempToken.substring(0, 3);
        hurricaneMonth[counter] = tempToken.substring(6, 8);
        hurricanePressure[counter] = Double.parseDouble(tempToken.substring(10, 12));
        hurricaneWindSpeed[counter] = Double.parseDouble(tempToken.substring(14, 16));
        hurricaneName[counter] = tempToken.substring(17);


        counter++;


   }
System.out.print("Lines: " + counter);
}
}

You could probably do something like this: 您可能会执行以下操作:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;







public class test {

    public void converter(String[] stringArray) {


        int counter = 0;
        String [] token = new String[1000];
        String [] tokenElements = new String[128];
        String [] hurricaneYear = new String[64];
        String [] hurricaneName = new String[64];
        String [] hurricaneMonth = new String[64];
        int []  hurricaneCategory = new int[64];
        double [] hurricanePressure = new double[64];
        double tempKnots;
        double knotsToMph; 
        double [] hurricaneWindSpeed = new double[64];
        double categoryAverage;
        double pressureAverage;
        double speedAverage; 
        String headerData = "                          Hurricanes 1980 - 2006\n\n Year         Hurricane       Category        Pressure(MB)        Wind Speed     (MPH)\n========================================================================";
        Scanner in = new Scanner(System.in);
        Scanner inFile = null;
        try {
            inFile = new Scanner(new File("hurcData2.txt"));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }



        while(inFile.hasNextLine()){

          String line = inFile.nextLine();
          String[] arrayOfString = line.split(" "); 




           }
        System.out.print("Lines: " + counter);
        }




        }

The issue with incompatible types is because you have to convert the Scanner object to a String. 类型不兼容的问题是因为您必须将Scanner对象转换为String。 I did that in the while loop, so now while the scanner has a next line its going to turn that line into a string and split it on the spaces. 我在while循环中进行了此操作,所以现在扫描仪有下一行时,它将把该行转换为字符串并将其在空格处分割。 You will have an array for all the values. 您将拥有所有值的数组。 Now you can perform your logic based on the position in the array. 现在,您可以根据数组中的位置执行逻辑。

You can split the string into arrays with regex: 您可以使用正则表达式将字符串拆分为数组:

    String s = "1980 Aug    945 100 Allen";
    Pattern p = Pattern.compile("\\s+");
    System.out.println(Arrays.toString(p.split(s)));

or using the String.split method: 或使用String.split方法:

    System.out.println(Arrays.toString(s.split("\\s+")));

output: 输出:

[1980, Aug, 945, 100, Allen]
[1980, Aug, 945, 100, Allen]

The title of the question lists index out of bounds exception, but it does not say if it is StringIndexOutOfBoundsException or ArrayIndexOutOfBoundsException. 问题的标题列出了索引超出范围的异常,但没有说明它是StringIndexOutOfBoundsException还是ArrayIndexOutOfBoundsException。

You read the lines into an array that is defined to hold 1000 elements, but then put the parsed pieces of the string into arrays that are only defined to hold 64 elements. 您将这些行读入定义为可容纳1000个元素的数组中,然后将字符串的已解析部分放入仅定义为可容纳64个元素的数组中。

It could be that your parsing logic is OK but the array's are getting over filled. 可能是您的解析逻辑还可以,但数组已满。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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