gpt4 book ai didi

java - 从文件中读取 float

转载 作者:行者123 更新时间:2023-12-01 18:36:12 25 4
gpt4 key购买 nike

如何从文件中读取 float ?

  0.00000E+00  2.12863E-01
1.00000E-02 2.16248E-01
2.00000E-02 2.19634E-01

在文件中,第一列数字之前和数字之间有 2 个空格。我立即出现错误:

s = new Scanner(new File("P0"));
while (s.hasNext()) {
float x = s.nextFloat();
float y = s.nextFloat();

System.out.println("x = " + x + ", y = " + y);
}

最佳答案

  1. 逐行读取文件。
  2. 根据空格将每行拆分为单词。
  3. 将每个单词转换为 float 。

这是代码:

    BufferedReader reader = null;

try {
// use buffered reader to read line by line
reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(
"<FULL_FILE_PATH>"))));

float x, y;
String line = null;
String[] numbers = null;
// read line by line till end of file
while ((line = reader.readLine()) != null) {
// split each line based on regular expression having
// "any digit followed by one or more spaces".

numbers = line.split("\\d\\s+");

x = Float.valueOf(numbers[0].trim());
y = Float.valueOf(numbers[1].trim());

System.out.println("x:" + x + " y:" + y);
}
} catch (IOException e) {
System.err.println("Exception:" + e.toString());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.err.println("Exception:" + e.toString());
}
}
}

关于java - 从文件中读取 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21918275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com