您好我在读取此项目的CSV文本文件时收到NumberFormatException错误。这是CSV
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
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
我对将要发生的事情有一个大致的了解。出现错误我相信因为它到达第一行的末尾然后弹出错误
Exception in thread "main" java.lang.NumberFormatException: For input
string: "2 24680"
这是我到目前为止所做的:
import java.io.*;
import java.util.*;
public class Prog7
{
public static void main(String[] args)
{
String warehouseID = null;
String city = null;
String state = null;
int partNumber = 0;
String description = null;
double price = 0.0;
int quantity = 0;
int count = 0;
int numWarehouse = 4;
int numParts = 13;
Scanner warehouseFile = null;
Scanner partFile = null;
Warehouse[] warehouse = new Warehouse[10];
Part[] parts = new Part[20];
try
{
warehouseFile = new Scanner(new File("warehouse.txt"));
while (warehouseFile.hasNext())
{
warehouseID = warehouseFile.next();
city = warehouseFile.next();
state = warehouseFile.next();
warehouse[count] = new Warehouse(warehouseID, city, state);
count++;
}
partFile = new Scanner(new File("parts.txt"));
partFile.useDelimiter(",");
while (partFile.hasNext())
{
partNumber = Integer.parseInt(partFile.next());
description = partFile.next();
price = Double.parseDouble(partFile.next());
warehouseID = partFile.next();
quantity = Integer.parseInt(partFile.next());
parts[count] = new Part(partNumber, description, price, warehouseID, quantity);
count++;
}
}
catch (FileNotFoundException e)
{
System.err.print("warehouse.txt or parts.txt not found");
}
for (int i = 0; i < numWarehouse; i++)
{
System.out.printf("%5s %5s %5s\n", warehouse[i].getWarehouseID(), warehouse[i].getCity(),
warehouse[i].getState());
for (int j = 0; j < numParts; j++)
{
if (parts[j].getWarehouseID().equals(warehouse[i].getWarehouseID()))
{
System.out.printf("%5s %5s %10.2f %5\nd", parts[j].getPartNumber(), parts[j].getDescription(),
parts[j].getPrice(), parts[j].getQuantity());
}
}
}
}
}
我认为它与程序有关,就是读取每个值,但是没有什么可以进入下一行。我有一个尝试过partFile.nextLine()指令和一个hasNextLine()while循环,我仍然得到相同的错误。或许我可以用换行符进行操作吗?
答案 0 :(得分:0)
我认为问题在于:
partFile.useDelimiter(",");
您告诉扫描仪只能用逗号分割。一旦到达parts.txt
第一行中的最后一项,它就会向前读取,直到找到下一行中的第一个逗号,然后返回2
,然后返回行尾,后跟{ {1}}作为下一个项目。
您不仅想要用逗号分割,还想用换行符分割。 useDelimiter
采用正则表达式:以下内容告诉扫描程序拆分逗号或换行符的任意组合:
24680
答案 1 :(得分:0)
除了Luke Woodward的回答,也许你应该考虑到2018年,而不是1999年。以下代码应该做你正在寻找的东西,知道如何解析一条线移动到它所属的类中。我把它作为构造函数,但它也可以是静态valueOf
方法。
Path warehouseFile = Paths.get("warehouse.txt");
Files.lines(warehouseFile)
.map(Warehouse::new)
.collect(toList());
static class Warehouse {
public Warehouse(String line) {...}
}