简体   繁体   中英

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.

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.

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