【发布时间】:2018-05-06 10:20:40
【问题描述】:
这是我的文本文件:
1,2,3
4,5,6,7
这是我的代码 sn-p:
import java.io.*;
import java.util.*;
public class Findcycle {
private final static String DELIMITER = ",";
private final static String filePath = "D:\\1.txt";
public static void main(String[] args) {
File inputFile = new File(filePath);
ArrayList<Integer> numbers = new ArrayList<Integer>();
try
{
Scanner scanner = new Scanner(inputFile);
scanner.useDelimiter(DELIMITER);
while(scanner.hasNext())
{
String value = scanner.next();
Integer num = Integer.parseInt(value);
numbers.add(num);
}
System.out.println(numbers);
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
我收到以下异常:
线程“main”java.lang.NumberFormatException 中的异常:对于输入 字符串:“3 4”在 java.lang.NumberFormatException.forInputString(未知来源)
在 java.lang.Integer.parseInt(未知来源)
在 java.lang.Integer.parseInt(未知来源) 在 Findcycle.main(Findcycle.java:18)
我该怎么办?
【问题讨论】:
-
"3 4" 不是一个数字,而是两个!那么这个由空格而不是逗号分隔的特定条目的确切含义是什么?另外,这段代码中的二维列表在哪里?
-
这看起来像是一个错字。这张票可以关闭。
-
next()返回非分隔符标记,但如果您仅将分隔符设置为,,则您不会将行分隔符或其他空格作为分隔符的一部分。根据您想要实现的目标,您可以使用",|\\s+"之类的分隔符,它是代表,或one or more whitespaces的正则表达式。
标签: java exception text-files numberformatexception