我在閱讀和存儲文本文件中的整數時遇到問題。我正在使用一個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