0

我有一个 csv,我试图将其读入对象数组。我不断收到以下错误... java.util.InputMismatchException 我认为这是因为它读取的文件由空格而不是逗号分隔。我相信我需要使用 String.split() 方法,但我不确定该怎么做。有什么建议么。这是我到目前为止的代码......

public class Prog7
{
public static void main(String[] args)
{
    Part[] parts;
    int numParts;
    int partNumber;
    String description;
    double price;
    int quantity;
    String city;

    parts = new Part[100];
    numParts = 0;

    Scanner inFile = null;

    /*
     * open file
     */
    try
    {
        inFile = new Scanner( new File( "C:/COSC        210/Assignment#7/parts.txt" ) );
    }
    catch ( FileNotFoundException e )
    {
        System.err.println( "Error: file not found" );
    }

    /*
     * read file using each record to create a State object
     * and add that State object to the PopulationData object
     */
    while( inFile.hasNext() )
    {
        partNumber = inFile.nextInt();
        description = inFile.next();
        price = inFile.nextDouble();
        city = inFile.next();
        quantity = inFile.nextInt();


        Part p = new Part(partNumber, description, price, 
                          quantity, city);
        parts[numParts]= p;
        numParts++;

        for (int i = 0; i < numParts; i++)
        {
            System.out.println(parts[i].getPartNumber());
        }
    }
}
}

以下是我正在使用的文本文件:

12345,Left-Handed Bacon Stretcher,125.95,PGH,2

24680,Smoke Shifter,0.98,PGH,48

86420, Pre-dug Post Hole,2.49,ATL,34

25632,Acme Widget,98.29,LOU,342

97531,Anti-Gravity Turbine,895.29,ATL,3

24680,Battery-Powered Battery Charger,252.98,ATL,2

12345,Left-Handed Bacon Stretcher,125.95,LOU,35

97531,Anti-Gravity Turbine,895.29,PHL,8

00000,Glass Hammer,105.90,PGH,8

86420, Pre-dug Post Hole, 2.49,ATL,34

01020,Inflatable Dartboard,32.95,PGH,453

86420, Pre-dug Post Hole, 2.49,LOU,68

86420, Pre-dug Post Hole, 2.49,PGH,124

24680, Battery-Powered Battery Charger, 252.98, PHL, 5
4

2 回答 2

3

利用scanner.useDelimiter(",");

    Scanner inFile = new Scanner(new File
                          ("C:/COSC        210/Assignment#7/parts.txt" ));
    inFile.useDelimiter(",");
    while (inFile.hasNext()) {
        int partNumber = Integer.parseInt(inFile.next());
        String description = inFile.next();
        double price = Double.parseDouble(inFile.next());
        String city = inFile.next();
        int quantity = Integer.parseInt(inFile.nextLine().replaceAll(",", ""));
        if(inFile.hasNextLine()) inFile.nextLine();
        System.out.println(partNumber+","
                +description+","
                +price+","
                +city+","
                +quantity);
    }
    inFile.close();
于 2013-04-17T04:14:24.277 回答
0

扫描仪默认使用空格作为分隔符。scanner.useDelimiter(",")在阅读文件之前使用。

它仍然不是万无一失的,因为内容本身可以拥有","

如果它用于学习,那么它很好,否则你可以考虑使用一些已经这样做的库,例如http://sourceforge.net/projects/opencsv/files/opencsv/

另外,不要使用固定的 100 长度数组,而是使用List,就好像记录超过一百个一样,您的代码会因异常而中断。

于 2013-04-17T04:16:04.533 回答