简体   繁体   English

java将文件中的数据存储到单独的数组中

[英]java storing data from file into separate array

I have a question on how to store data from a file into separate arrays. 我对如何将文件中的数据存储到单独的数组中有一个疑问。 In my case, I need to read a file and store the data into separate arrays, one for the name of the hurricane, the wind speed, the pressure, and the year. 以我为例,我需要读取一个文件并将数据存储到单独的数组中,其中一个数组用于飓风的名称,风速,压力和年份。 Below is my code that I have so far: 以下是我到目前为止的代码:

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

public class Hurricanes2 {

public static void main(String args[]) throws IOException{

    // create token1
    String token1 = "";

    // create Scanner inFile
    Scanner inFile = new Scanner(new File("/Users/timothylee/hurcdata2.txt"));

    // while statment
    while(inFile.hasNext()){

        // initialize token1
        token1 = inFile.next();
    }

    // close inFile
    inFile.close();
}

}

and my file contains this: 我的文件包含以下内容:

1980 Aug    945 100 Allen
1983 Aug    962 100 Alicia
1984 Sep    949 100 Diana
1985 Jul    1002    65  Bob
1985 Aug    987 80  Danny
1985 Sep    959 100 Elena
1985 Sep    942 90  Gloria

Any help will be greatly appreciated. 任何帮助将不胜感激。

have you heard of regular expressions? 您听说过正则表达式吗? Using a tokens array, two string arrays and the regular expression \\s+ you can parse the input. 使用令牌数组,两个字符串数组和正则表达式\\ s +,您可以解析输入。

I would have something like 我会有类似的东西

    String tokens[];
    String input;
    String date[10] = new String[10];
    String hurricaneName[10] = new String[10];
    int count = 0;
    String temp;

      // while statment
input = inFile.hasNext()
while(input != null){
     tokens = input.split("\\s+");
     // the above line splits the input up at every white space
     // use this to put appropriate data into proper arrays for example
     temp = tokens[0] + tokens[1];
     date[count] = temp;

     hurricaneName[count] = tokens[5];         

    count ++;
    token1 = inFile.next();
}

I would say 我会说

String temp = "";
List yearList = new ArrayList();
List pressureList = new ArrayList();
List speedList = new ArrayList();
List nameList = new ArrayList();

while (temp = inFile.nextLine())
{
    String[] stemp = temp.split(" ");
    yearList.add(stemp[0]);
    //skipping the month
    pressureList.add(stemp[2]);
    speedList.add(stemp[3]);
    nameList.add(stemp[4]);
}

Now the indices for each ArrayList correspond to one another and can easily be iterated through in a for loop. 现在,每个ArrayList的索引都彼此对应,并且可以在for循环中轻松地进行迭代。

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

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