我在阅读和存储文本文件中的整数时遇到问题。我正在使用一个int数组,所以我想在没有列表的情况下执行此操作。我收到一个输入不匹配异常,我不知道该如何解决这个问题。正在读取的文本文件也包含字符串。从txt文件读取整数并存储到数组中
public static Integer[] readFileReturnIntegers(String filename) {
Integer[] array = new Integer[1000];
int i = 0;
//connect to the file
File file = new File(filename);
Scanner inputFile = null;
try {
inputFile = new Scanner(file);
}
//If file not found-error message
catch (FileNotFoundException Exception) {
System.out.println("File not found!");
}
//if connected, read file
if(inputFile != null){
System.out.print("number of integers in file \""
+ filename + "\" = \n");
//loop through file for integers and store in array
while (inputFile.hasNext()) {
array[i] = inputFile.nextInt();
i++;
}
inputFile.close();
}
return array;
}
发表您的文本文件的内容... – gowtham
检查'next()'[isNumeric](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#isNumeric%28java.lang.CharSequence %29) –
'hasNextInt()'when using nextInt()'.. – 2014-01-23 06:06:12