简体   繁体   English

Java如何从具有多个字符串和双精度值的文本文件中读取一行?

[英]Java how to read a line from a text file that has multiple strings and double values?

I want to create a program that reads from a text file with three different parts and then outputs the name. 我想创建一个程序,该程序从具有三个不同部分的文本文件中读取内容,然后输出名称。 Eg text file: 例如,文本文件:

vanilla   12   24
chocolate   23  20
chocolate chip  12   12

However, there is a bit of an issue on the third line, as there is a space. 但是,由于存在空格,第三行存在一些问题。 So far, my code works for the first two lines, but then throws a InputMismatchException on the third one. 到目前为止,我的代码适用于前两行,但随后在第三行上引发了InputMismatchException。 How do I make it so it reads both words from one line and then outputs it? 我如何做到这一点,以便它从一行中读取两个单词,然后将其输出? My relevant code: 我的相关代码:

    while (in.hasNext())
{
    iceCreamFlavor = in.next();
    iceCreamRadius = in.nextDouble();
    iceCreamHeight = in.nextDouble();

out.println("Ice Cream: " + iceCreamFlavor);
}

In your input file, the separator between fields is composed of multiples spaces, no ? 在您的输入文件中,字段之间的分隔符由多个空格组成,不是吗? if yes, you could simply use split method of String object. 如果是,则可以简单地使用String对象的split方法。

You read a line. 您读了一行。 You split it to obtain a String array. 您将其拆分以获得String数组。

String[] splitString = myString.split("   ");

Ther first element «0» is the String, the two others can be parsed as double 第一个元素“ 0”是字符串,其他两个元素可以解析为双精度

This could looks like : 可能看起来像:

    try (BufferedReader br = new BufferedReader(new FileReader("path/to/the/file.txt"))) {
        String line;
        while ((line = br.readLine()) != null) {
            String[] lineSplitted = line.split("   ");
            String label = lineSplitted[0];
            double d1 = Double.parseDouble(lineSplitted[1]);
            double d2 = Double.parseDouble(lineSplitted[2]);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

You can use scanner.useDelimiter to change the delimiter or use a regular expression to parse the line. 您可以使用scanner.useDelimiter更改定界符或使用正则表达式来解析该行。

//sets delimiter to 2 or more consecutive spaces
Scanner s = new Scanner(input).useDelimiter("(\\s){2-}");

Check the Scanner Javadoc for examples: 查看扫描仪Javadoc中的示例:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM