我有一个 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