简体   繁体   English

(Java)扫描程序无法从文件中读取nextDouble()

[英](Java) Scanner not reading in nextDouble() from file

I'm new to Java and I'm trying to use a scanner to read in some data from a text file. 我是Java的新手,我正在尝试使用扫描程序从文本文件中读取一些数据。 The scanner reads in the string and integer data members fine, but when it reaches a double it throws an InputMismatchException. 扫描程序读取字符串和整数数据成员,但是当它达到double时会抛出InputMismatchException。

The format of the text file looks like this... 文本文件的格式如下所示......

Lastname,Firstname,0,0.0 姓氏,名字,0,0.0
Smith,John,10,2.456 史密斯,约翰,10,2.456
Jones,William,15,3.568 琼斯,威廉,15,3.568

Here is my code... 这是我的代码......

import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;

public class Student {

    int age;
    double gpa;
    String firstName;
    String lastName;

    public static void main (String[] args) {
        int iNum = 0;
        double dNum = 0.0;
        String str1 = "";
        String str2 = "";
        List<Student> listOfObjects = new ArrayList<>();

        try {
            Scanner src = new Scanner(new
                     File("data.txt")).useDelimiter(",|\r\n|\n");

            while (src.hasNext()) {
                str1 = src.next();  //last name
                str2 = src.next();  //first name
                iNum = src.nextInt();  //age
                dNum = src.nextDouble();  /* gpa - having trouble reading these doubles with Scanner */             

                Student object = new Student(str1, str2, iNum, dNum);
                listOfObjects.add(object); //add new object to list

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

        for (Student a: listOfObjects)   // printing the sorted list
            System.out.print(a.getStudentLastName() + ", " +  
            a.getStudentFirstName() +
            ", " + a.getStudentAge() + ", " + a.getStudentGpa() + "\n");
    }

    public Student(String str1, String str2, int iNum, double dNum){
        this.lastName = str1;
        this.firstName = str2;
        this.age = iNum;
        this.gpa = dNum;
    }

    public String getStudentFirstName() {
        return firstName;
    }

    public String getStudentLastName() {
        return lastName;
    }

    public int getStudentAge() {
        return age;
    }

    public double getStudentGpa() {
        return gpa;
    }

I tried setting the locale to US and tried messing with the delimiters, but nothing seems to be working. 我尝试将语言环境设置为美国并试图弄乱分隔符,但似乎没有任何工作。

Big thanks to @Sotirios for calling out my incorrect closing of the question. 非常感谢@Sotirios呼吁我不正确地结束这个问题。 Your problem is being caused by using an incorrect pattern in your scanner. 您的问题是由扫描仪中使用不正确的图案引起的。 Based on the snippet of the input file you showed us, there are spaces after each comma. 根据您向我们展示了输入文件的片断,还有每个逗号后的空格 Hence, you should be using the following pattern to reflect this: 因此,您应该使用以下模式来反映这一点:

,\\s*|\r\n|\n
^^^^^ match a comma, followed by zero or more spaces

When I tested locally, I didn't even get as far as the double value, it crashed when reading the third position integer. 当我在本地测试时,我甚至没有达到double值,它在读取第三个位置整数时崩溃了。 Try the following code: 请尝试以下代码:

Scanner src = new Scanner(new File("data.txt")).useDelimiter(",\\s*|\r\n|\n");
while (src.hasNext()) {
    str1 = src.next();
    str2 = src.next();
    iNum = src.nextInt();
    dNum = src.nextDouble();

    Student object = new Student(str1, str2, iNum, dNum);
    listOfObjects.add(object); //add new object to list
}

The reason the first two strings were getting through is that the space after the comma was being rolled up into the next string. 前两个字符串通过的原因是逗号之后的空格被卷入下一个字符串。 But you don't get away with this with numbers, in which case the extra whitespace had nowhere to go and you ended up with the InputMismatchException you kept seeing. 但是你没有用数字来逃避这种情况,在这种情况下,额外的空白无处可去,你最终得到了你一直看到的InputMismatchException

I resolved the issue. 我解决了这个问题。 The delimiter pattern I was using looked like this (",|\\r\\n|\\n"). 我使用的分隔符模式看起来像这样(“,| \\ r \\ n | \\ n”)。 So the scanner wasn't seeing a double, but instead was including it in the string with the last name separated by a carriage return. 因此,扫描仪没有看到双重,而是将其包含在字符串中,其姓氏由回车符分隔。

The simple fix for this was to include a carriage return in the pattern. 对此的简单修复是在模式中包含回车。

The new pattern looks like this - (",|\\r\\n|\\n|\\r") 新模式看起来像这样 - (“,| \\ r \\ n | \\ n | \\ r \\ n”)

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

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