英文:
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();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论