简体   繁体   中英

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:

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

The Scanner class will read 'tokens'. 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. If that works, that's what you get. If it doesn't, you get an 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). Furthermore, that comma is in your strings, and I bet you didn't want that.

Scanner works by separating tokens using a delimiter . 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. This one reads: EITHER [a] Any amount of whitespace, then a comma, then any amount of whitespace, OR [b] a newline.

Because the item name can be more than one word, I recommend using a method called 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"]. In your example, the string that you would perform this operation on would be obtained by using 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]).

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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