繁体   English   中英

NumberFormat Java解析错误

[英]NumberFormat Java parse error

使用类NumberFormat解析我的数据时遇到麻烦:

Cocacola 10 50
Tea 10 50
Water 10 50
Milk 10 50
Soda 10 50

我检查了readLine()并正确读取,但是当我解析为双精度或整数值并打印时,这是错误的,这是标准输出:

Cocacola 1.0 5 
Tea 1.0 5 
Water 1.0 5 
Milk 2.0 5 
Soda 1.0 5 

和代码:

String tmp[] = line.split("\\s+");
String name = tmp[0];
double cost=0;
int number=0;
NumberFormat nf = NumberFormat.getInstance();
try {
    cost = nf.parse(tmp[1].trim()).doubleValue();
    number=nf.parse(tmp[2].trim()).intValue();
} catch (ParseException e) {
    e.printStackTrace();
}
System.out.println(name+" "+cost+" "+number+" ");

我不能使用常规解析( Double.parse()Integer.parse()等),因为它们会使NumberFormatException错误。

如果在输入中尝试使用此文件会怎样?

Cocacola 10 50
GreenTea 10 50
Water 10 50
MilkTea 10 50
Soda 10 50

可能只是空白(和拆分)产生了错误,即:“ Green Tea”,“ Milk Tea”,...这行“ Green Tea 10 50”中的split函数生成tmp["Green","Tea","10","50"]和以下代码行:

cost = nf.parse(tmp[1].trim()).doubleValue();

您正在尝试解析以对字符串“ Tea”进行编号。

您的问题与以下事实有关:您的名称中间可能有空格,因此使用line.split("\\\\s+")无效,因为您可能会在代码预期的情况下获取length大于3String数组长度恰好是3

您应该使用正则表达式定义行的预期格式,如下所示:

// Meaning a sequence of any characters followed by a space
// then a double followed by a space and finally an integer 
Pattern pattern = Pattern.compile("^(.*) (\\d+(?:\\.\\d+)?) (\\d+)$");
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
    String name = matcher.group(1);
    double cost = Double.valueOf(matcher.group(2));
    int number = Integer.valueOf(matcher.group(3));
    System.out.printf("%s %f %d%n", name, cost, number);
} else {
    throw new IllegalStateException(
        String.format("line '%s' doesn't have the expected format", line)
    );
}

我猜您应该使用2种不同的格式,一种用于价格,另一种用于数量。 您可以尝试以下方法:

NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH);
try {
    cost = nf.parse(tmp[1].trim())).doubleValue();
    number = nf.parse(tmp[2].trim()).intValue();
} catch (ParseException e) {
    e.printStackTrace();
}

如果您完全尝试此代码:

NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.ENGLISH);
double d = numberFormat.parse("10").doubleValue();
int q = numberFormat.parse("50").intValue();
System.out.println("Cost: " + d);
System.out.println("Quantity: " + q);

输出为:

10.0 50

不是您想要的代码吗?

暂无
暂无

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

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