Integer.parseInt(String)抛出一个NumberFormatExpression。

huangapple go评论99阅读模式
英文:

Integer.parseInt(String) throws a NumberFormatExpression

问题

我从一个包含项目名称和数量的文件中读取数据。当我尝试将数量转换为整数时,出现了NumberFormatExpression异常。我觉得这可能是由于-符号引起的,但即使去掉-,它仍然会引发异常。

String line = reader.readLine();

while (line != null) {
    String[] delimiter = line.split(",");
    int originalQuantity = Integer.parseInt(delimiter[1]);
    line = reader.readLine();
}

文件内容:

卫生纸, -10
洗手液, 12
英文:

I'm reading in from a file that contains an item name and its quantity. I'm getting a NumberFormatExpression when I try to convert the quantity amount to an int. I feel it may be due to the - sign, but even after removing the - it stills throws the exception

String line = reader.readLine();

while (line != null) {
	String[] delimiter = line.split(",");
	int originalQuantity = Integer.parseInt(delimiter[1]);
	line = reader.readLine();
}

the file contents:

Toilet Papers, -10
Hand sanitizers, 12

答案1

得分: 3

你在数字前面包含了一个空格。使用 trim 方法去掉它。

String line = reader.readLine();
while (line != null) {
    String[] delimiter = line.split(",");
    int originalQuantity = Integer.parseInt(delimiter[1].trim()); // 在这里使用 trim
    line = reader.readLine();
}
英文:

You're including a space at the beginning of the number. Use the trim method to get rid of it.

String line = reader.readLine();
while (line != null) {
    String[] delimiter = line.split(",");
    int originalQuantity = Integer.parseInt(delimiter[1].trim()); // <-- trim here
    line = reader.readLine();
}

huangapple
  • 本文由 发表于 2020年10月28日 00:48:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/64559158.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定