如何从文件读取浮点值并初始化数组?

时间:2019-01-31 19:47:09

标签: java

我正在尝试从.txt文件中读取浮点值以初始化数组,但它会引发InputMismatchException

这是我要从文件中读取的方法和样本值是4 2 1 4

    public class Numbers {
    private Float [] numbers;
    public int default_size = 10;
    String fileName = new String();

    public void initValuesFromFile()
    {
        Scanner scan = new Scanner(System.in); 
        fileName = scan.next();
        BufferedReader reader = null;
        try {
            reader  = new BufferedReader (new FileReader(fileName));
            String input = null;

            while ((input = reader.readLine()) != null) {
                for (int i = 0; i < numbers.length; i++) {
                    numbers[i] = Float.parseFloat(input);
        }
        }
    }
        catch (NumberFormatException | IOException e) {
            e.printStackTrace();
     }
    }

}

1 个答案:

答案 0 :(得分:2)

您需要从文件中读取一行,并使用空格甚至更好的\\s+进行拆分,然后对所有拆分为字符串数组的项目运行一个for循环,然后解析每个数字并将其存储在{{1 }},即使您在不同的行中有多个数字,也可以使用这种方法。这是您需要尝试的代码,

List<Float>

此打印,

Float[] numbers = new Float[4];
Scanner scan = new Scanner(System.in);
String fileName = scan.next();
scan.close();
BufferedReader reader = null;
try {
    reader = new BufferedReader(new FileReader(fileName));
    String input = null;

    while ((input = reader.readLine()) != null) {
        String nums[] = input.trim().split("\\s+");
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = Float.parseFloat(nums[i]);
        }
        break;
    }
    System.out.println(Arrays.toString(numbers));
} catch (NumberFormatException | IOException e) {
    e.printStackTrace();
}