考虑一下这样的文本文件:
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}
答案 0 :(得分:0)
// 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();
}
将它们放入数组后,它将转到下一行。 那应该按照你想要的方式读取你的文件。
答案 1 :(得分:0)
// 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();
}