简体   繁体   English

如果它们在同一行上,是否可以读取字符串和数字(来自 TXT 文件)

[英]Is it possible to read a String and Numbers if they're on the same line (From a TXT file)

I had a hard time wording the title of my question.我很难说出我的问题的标题。

In my given assignment I need to write a program to read from a text file.在我给定的作业中,我需要编写一个程序来读取文本文件。

For example: (This is in the textfile, the numbers being the price of the item.)例如:(这是在文本文件中,数字是商品的价格。)

Cappuccino, 3.50

Espresso, 2.10

Mochaccino, 5.99

Irish Coffee, 7.99

Caffe Americano, 6.40

Latte, 1.99

This is my code to read the text file:这是我读取文本文件的代码:

public void readFile(){
        while(x.hasNext()){
            String item = x.next();
            Double price = x.nextDouble();

            System.out.printf("%s $%.2f \n", item, price);

        }//end of whileLoop
    }

    public void closeFile(){
        x.close();
    }

My Output:我的 Output:

Cappuccino, $3.50
Espresso, $2.10
Mochaccino, $5.99
Exception in thread "main" java.util.InputMismatchException
        at java.base/java.util.Scanner.throwFor(Scanner.java:939)
        at java.base/java.util.Scanner.next(Scanner.java:1594)
        at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
        at ReadTextFile.readFile(MiniProject.java:22)
        at MiniProject.main(MiniProject.java:400)

The code works well, and expected until it reaches a menu item with two words, rather than a singular word.该代码运行良好,并且预期直到它到达一个包含两个单词而不是单数单词的菜单项。 How could I change my code to read both words before reading the price?在阅读价格之前,我如何更改我的代码以阅读这两个词?

Here is a video of how I'd like my program to be able to read the file - https://youtu.be/gIMxwKc-pw8这是我希望我的程序能够读取文件的视频 - https://youtu.be/gIMxwKc-pw8

The Scanner class will read 'tokens'. Scanner class 将读取“令牌”。 When you call nextDouble , it will read a token without caring if it is a double or a string or whatnot, and will then attempt to convert it to a double.当您调用nextDouble时,它会读取一个标记,而不关心它是一个双精度数还是一个字符串或诸如此类,然后会尝试将其转换为双精度数。 If that works, that's what you get.如果这行得通,那就是你得到的。 If it doesn't, you get an InputMismatchException .如果没有,你会得到一个InputMismatchException

So, what you want to accomplish here is that Irish Coffee is a single token (or possibly that your code is updated to keep reading tokens and concatenate them, that sounds more complicated).所以,你想要在这里完成的是Irish Coffee是一个单一的标记(或者可能你的代码被更新以继续读取标记并将它们连接起来,这听起来更复杂)。 Furthermore, that comma is in your strings, and I bet you didn't want that.此外,那个逗号在你的字符串中,我打赌你不想要那个。

Scanner works by separating tokens using a delimiter . Scanner 通过使用分隔符分隔标记来工作。 Out of the box, the delimiter is 'any amount of whitespace' (so, spaces and newlines).开箱即用,分隔符是“任意数量的空格”(因此,空格和换行符)。

It sounds like what you need here is to redefine the delimiter: It is either a comma surrounded by any amount of whitespace, OR a newline:听起来您需要在这里重新定义分隔符:它可以是被任意数量的空格包围的逗号,也可以是换行符:

scanner.useDelimiter("(\\s*,\\s*)|\r?\n");

would do the job.会做这项工作。 That gobbledygook in the middle is a regex.中间的那个 gobbledygook 是一个正则表达式。 This one reads: EITHER [a] Any amount of whitespace, then a comma, then any amount of whitespace, OR [b] a newline.这个内容如下: [a] 任意数量的空格,然后是逗号,然后是任意数量的空格,或者 [b] 换行符。

Because the item name can be more than one word, I recommend using a method called split().因为项目名称可以多于一个单词,所以我推荐使用一种叫做 split() 的方法。 This will split the line based on a certain string and return an array of the parts of the string split on the value you gave the method.这将根据某个字符串拆分行,并根据您给该方法的值返回字符串拆分部分的数组。 For example, "I do, a".split(", ") will split on a comma followed by a space and return the array ["I do", "a"].例如,"I do, a".split(", ") 将在逗号后跟空格处拆分并返回数组 ["I do", "a"]。 In your example, the string that you would perform this operation on would be obtained by using scan.nextLine().在您的示例中,您将执行此操作的字符串将通过使用 scan.nextLine() 获得。 Then you have the first portion and the second portion that you are interested in. To convert the second element of the array to a double, you can use Double.parseDouble(arr[1]).然后你有你感兴趣的第一部分和第二部分。要将数组的第二个元素转换为双精度,可以使用 Double.parseDouble(arr[1])。

This code would work:此代码将起作用:

public void readFile(){
    while(x.hasNextLine()){
        String[] nextLineArr = x.nextLine().split(", ");
        String item = nextLineArr[0];
        double price = Double.parseDouble(nextLineArr[1]);

        System.out.printf("%s $%.2f %n", item, price);

    }//end of whileLoop
}

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

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