[英]java storing data from file into separate array
我對如何將文件中的數據存儲到單獨的數組中有一個疑問。 以我為例,我需要讀取一個文件並將數據存儲到單獨的數組中,其中一個數組用於颶風的名稱,風速,壓力和年份。 以下是我到目前為止的代碼:
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();
}
}
我的文件包含以下內容:
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
任何幫助將不勝感激。
您聽說過正則表達式嗎? 使用令牌數組,兩個字符串數組和正則表達式\\ s +,您可以解析輸入。
我會有類似的東西
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();
}
我會說
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]);
}
現在,每個ArrayList的索引都彼此對應,並且可以在for循環中輕松地進行迭代。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.