【发布时间】:2014-02-14 21:04:57
【问题描述】:
我正在尝试循环遍历整数的文本文件并将找到的整数存储到数组中。
使用 try-catch 来确定哪些单词是整数,哪些不是使用 InputMismatchException,从输入流中删除非整数字符串。以及文件中空行的 NoSuchElementException。 我的主要问题是在我的第二种方法中存储整数并在数组中打印这些整数 :o 。看来我的循环也将非整数记录为空。他们不应该被存储到数组中。
public static void main(String[] commandlineArgument) {
Integer[] array = ReadFile6.readFileReturnIntegers(commandlineArgument[0]);
ReadFile6.printArrayAndIntegerCount(array, commandlineArgument[0]);
}
public static Integer[] readFileReturnIntegers(String filename) {
Integer[] array = new Integer[1000];
// 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) {
// loop through file for integers and store in array
while (inputFile.hasNextLine()) {
for(int i = 0; i<array.length; i++)
{
try{
array[i] = inputFile.nextInt();
}
catch(InputMismatchException excep1)
{
String word = inputFile.next();
}
catch(NoSuchElementException excep2){
}
}
}
}
return array;
}
public static void printArrayAndIntegerCount(Integer[] array, String filename) {
//prints number of integers from file
//prints each integer in array
}
}
【问题讨论】:
-
您是否允许使用
List而不是Array,因为您的数组长度在此处始终为1000,并且很难说出您实际存储在该数组中的整数数量。 -
遗憾的是没有列表,尽管这会使事情变得更容易。我需要使用一个数组:o
标签: java arrays exception file-io java.util.scanner