简体   繁体   English

使用扫描仪从文件读取时出现InputMismatchException

[英]InputMismatchException while using Scanner to read from file

New to Java. Java的新手。 I'm having a hard time understanding why my code isn't running. 我很难理解为什么我的代码没有运行。 I'm getting a InputMismatchException when I try to run my code. 当我尝试运行代码时,出现InputMismatchException异常。

I did some testing and problems occur if there's white space in my file such as "New York." 我做了一些测试,如果文件中有空白,例如“ New York”,则会出现问题。 I've been trying different things such as looping with .hasNextLine() instead of .hasnext() as suggested in other threads but to no avail. 我一直在尝试不同的事情,例如用.hasNextLine()而不是其他线程中建议的.hasnext()循环,但无济于事。 Sometimes I can get it to run until the end it gives me a NoSuchElementException. 有时,我可以让它运行直到最后,它给了我NoSuchElementException。 If you could please put me in the right direction, that would help a lot thank you! 如果可以的话,请把我带到正确的方向,这将对您有所帮助!

import java.util.*;
import java.io.*;

public class StandaloneReport  {

    public static void main(String[] args) {

        String fileInputName;
        String fileOutputName;

        String firstName;
        String lastName;
        String houseNumber;
        String street;
        String city;
        String state;
        String zip;
        String productDescription;
        double productPrice;

        //Scanner obj1
        Scanner input = null;
        input = new Scanner(System.in);

        System.out.printf("What is the file name?\n");
        fileInputName = input.nextLine();

        //Print out the name user inputed
        System.out.println("File name is: " + fileInputName);

                //Read the file
        FileReader filereader;
        Scanner readInput = null;

        try {
            readInput = new Scanner(filereader = new FileReader(fileInputName));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        while (readInput.hasNext())
        {
            firstName = readInput.next();
            lastName = readInput.next();
            houseNumber = readInput.next();
            street = readInput.next();
            city = readInput.nextLine();
            state = readInput.next();
            zip = readInput.next();
            productDescription = readInput.nextLine();
            productPrice = readInput.nextDouble();

Textfile looks like this: 文本文件如下所示:

Jane
Doe
10
Broadway
New York
NY
10001
Galaxy S10
199.99
2
Samsung Bluetooth
29.99
1
Slim Fit Hard Plastic Case
2.99
2
Charger
17.99
3


Error I get: 错误我得到:

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextDouble(Unknown Source)
    at hey.bcs.hwk.purchases.standalonereport.StandaloneReport.main(StandaloneReport.java:55)

I expected it to read it smoothly so I can print it using PrintStream in another file but I cannot even get past this part. 我希望它能顺利阅读,因此可以在另一个文件中使用PrintStream进行打印,但我什至无法通过这部分。

This is for one set of data, one data item per line. 这是一组数据,每行一个数据项。 You have to make adjustments for multiple sets of data. 您必须对多组数据进行调整。

int i = 0;
while (readInput.hasNext())
{
    if (i == 0)
    {
        firstName = readInput.nextLine();
    }
    else if (i == 1)
    {
        lastName = readInput.nextLine();
    }
    else if (i == 2)
    {
        houseNumber = readInput.nextLine();
    }
    else if (i == 3)
    {
        street = readInput.nextLine();
    }
    else if (i == 4)
    {
        city = readInput.nextLineLine();
    }
    else if (i == 5)
    {
        state = readInput.nextLine();
    }
    else if (i == 6)
    {
        zip = readInput.nextLine();
    }
    else if (i == 7)
    {
        productDescription = readInput.nextLine();
    }
    else if (i == 8)
    {
        productPrice = readInput.nextDouble();
    }

i += 1;
} // End while

To be honest your program is problematic in so many ways. 老实说,您的程序在很多方面都存在问题。 But here's an explanation to fix the mismatch issue you mentioned. 但是,以下是解决您提到的不匹配问题的说明。

readInput.nextLine()

will read the remainder of the current line . 将读取当前行的其余部分 So after reading "Broadway" the Scanner stays in the same line and when you call nextLine, the Scanner yields whatever is left in the line for "Broadway", which is an empty String. 因此,在阅读“百老汇”之后,扫描程序会停留在同一行,当您调用nextLine时,扫描程序会产生“百老汇”行中剩余的任何内容,这是一个空字符串。

To avoid this situation, do 为了避免这种情况,请执行

street = readInput.next();
readInput.nextLine();

To drop the current line("Broadway" for example). 删除当前行(例如“ Broadway”)。 And then call 然后打电话

city = readInput.nextLine();

That way the program will read "New York" as you expected. 这样,程序将按您的预期显示“ New York”。 As Tom mentioned in the comments, for more details, look at the question asked here . 正如汤姆在评论中提到的那样,有关更多详细信息,请看这里的问题。

Apart from the Scanner issue, your program is ambiguous as to where it ends – you did not provide closing brackets. 除了扫描仪问题外,您的程序在结束位置上也模棱两可–您未提供右括号。 That while loop seems redundant considering that your input is broken: it ceases to match what you have in your code after the "199.99" line. 考虑到您的输入已损坏,虽然while循环似乎是多余的:“ 199.99”行之后它不再与您的代码匹配。 Please put your complete code on there and revise your sample input. 请在此处输入完整的代码,然后修改示例输入。

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

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