[英]Reading a text file and adding to array, but skipping specific parts (Java)
I have a text file which I want to extract floats from and add to an array, but I keep getting an error and I'm not sure how to solve it.我有一个文本文件,我想从中提取浮点数并添加到数组中,但我不断收到错误,我不知道如何解决它。 It's to do with the string (the x and y), but I'm not sure how to skip these and only add the floats to the array.这与字符串(x 和 y)有关,但我不确定如何跳过这些,只将浮点数添加到数组中。
My txt file:我的txt文件:
x, 19.0
y, 22.5
My code:我的代码:
public static void readParameters() throws FileNotFoundException{
Scanner inFile = new Scanner(new File(filename));
ArrayList<Float> values = new ArrayList<Float>();
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
String[] nums = line.trim().split("\\s+");
for (String num : nums) {
float token = Float.parseFloat(num);
values.add(token);
System.out.println(nums);
}
}
inFile.close();
}
Overall, I want my array to just have the two floats.总的来说,我希望我的数组只有两个浮点数。
The split("\\s+")
will return an array which contains values like ["x,", "19.0"]
for first row. split("\\s+")
将返回一个数组,其中包含第一行的["x,", "19.0"]
等值。 As you are trying to convert non-float value x,
to float its throwing exception.当您尝试将非浮点值x,
转换为浮动其抛出异常时。
Please try below code:请尝试以下代码:
public static void readParameters() throws FileNotFoundException{
Scanner inFile = new Scanner(new File(filename));
ArrayList<Float> values = new ArrayList<Float>();
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
String[] nums = line.trim().split("\\s+");
if(nums.length == 2 ) {
float token = Float.parseFloat(nums[1]);
values.add(token);
System.out.println(nums);
}
}
inFile.close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.