gpt4 book ai didi

java - 如何用Java从文件中读取数字?

转载 作者:行者123 更新时间:2023-12-01 14:48:20 27 4
gpt4 key购买 nike

我正在尝试读入文件,并且已成功读入名称,但读不到名称后面的数字。我需要将这些数字不转换为字符串,而是转换为 float 或 double 。更糟糕的是,我必须读入两个数字。请帮忙? (顺便说一句,在代码中我已经导入了必要的东西)

我必须阅读的内容示例:

麦当劳农场,118.8 45670

public class Popcorn{ 


public static void main (String [] args) throws IOException {


System.out.println("Enter the name of the file");
Scanner in = new Scanner(System.in);
String filename = in.next();
Scanner infile = new Scanner(new FileReader( filename)); //
String line = "" ;

//to get stuff from the file reader

while (infile.hasNextLine())
{ line= infile.nextLine();

// int endingIndex =line.indexOf(',');
// String fromName = line.substring(0, endingIndex); //this is to get the name of the farm
// if (fromName.length()>0){
// System.out.println (fromName);
// }
// else if (fromName.length()<= 0)
// System.out.println(""); some of the durdling that goes on
// }
while (infile.hasNextLine())
{
line= infile.nextLine().trim(); // added the call to trim to remove whitespace
if(line.length() > 0) // test to verify the line isn't blank
{
int endingIndex =line.indexOf(',');
String fromName = line.substring(0, endingIndex);
String rest = line.substring(endingIndex + 1);
// float numbers = Float.valueOf(rest.trim()).floatValue();
Scanner inLine = new Scanner(rest);

System.out.println(fromName);
}
}
}
}
}

最佳答案

我不知道您传入的文件是什么样的,但以“McDonlad's Farm , 118.8 45670”为例,您可以执行以下操作:

...
String rest = line.substring(endingIndex + 1);
String[] sValues = rest.split("[ \t]"); // split on all spaces and tabs
double[] dValues = new double[sValues.length];
for(int i = 0; i < sValues.length; i++) {
try {
dValues[i] = Double.parseDouble(sValues[i]);
} catch (NumberFormatException e) {
// some optional exceptionhandling if it's not
// guaranteed that all last fields contain doubles
}
}
...

dValues-数组应包含所有所需的 double (或浮点)值。

一些附加说明:除了jlordo已经说过的之外,如果您使用正确的缩进,您的代码将变得更易于阅读......

关于java - 如何用Java从文件中读取数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15158301/

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