想一想一个文本文件,比如:
line1 ->5
line2 ->A 10
line3 ->B 15
line4 ->C 25
line5 ->D 5
line6 ->E 30'5‘是{a,b,c,d,e}的数。如何将这些变量保存在两个数组中,如:
Array1[5] = {A,B,C,D,E}
Array2[5] = {10,15,25,5,30}发布于 2014-03-03 01:12:54
// read all lines in the file into a list
List<String> lines = Files.readAllLines(Paths.get("filename"), Charset.defaultCharset());
// determine the length of the arrays based on the first line
int length = Integer.parseInt(lines.remove(0));
// first column
String[] col1 = new String[length];
// second column
int [] col2 = new int[length];
// now for every remaining row, add to each column
for(int i = 0; i < length; i++){
String [] pair = lines.remove(0).split(" ");
col1[i] = pair[0];
col2[i] = Integer.parseInt(pair[1]);
}或者更容易..。
// create a scanner of the file
Scanner scan = new Scanner(new File("filename"));
// read the first token as an int to know array length
int length = scan.nextInt();
String [] col1 = new String[length];
int [] col2 = new int[length];
// assuming valid data, loop through each row
for(int i = 0; i < length; i++){
col1[i] = scan.next();
col2[i] = scan.nextInt();
}发布于 2014-03-03 00:57:42
// x=文件的内容
while(x.hasNext) {
String a = x.next(); // This will get the first bit (e.g A, B, C, etc)
String b = x.next(); // This will get the last bit (e.g 10, 15, 25, etc)
// now just put them in the array
// for every extra bit of data you have on a line you just add another String y = x.next();
}在将它们放到数组中之后,它将转到下一行。应该以你想要的方式读你的文件。
https://stackoverflow.com/questions/22135813
复制相似问题