【发布时间】:2014-01-23 07:32:31
【问题描述】:
我整天都在用这个程序来读取整数的文本文件并将整数存储到数组中。我想我终于用下面的代码得到了解决方案。
但不幸的是.. 我必须使用 hasNextLine() 方法遍历文件。 然后使用 nextInt() 从文件中读取整数并将它们存储到数组中。 所以使用扫描仪构造函数,hasNextLine()、next() 和 nextInt() 方法。
然后使用try and catch 来确定哪些单词是整数,哪些不是,使用 InputMismatchException。文件中的空行也是一个例外? 问题是我没有使用 try 和 catch 和异常,因为我只是跳过了非整数。 另外,我使用的是 int 数组,所以我想在没有列表的情况下执行此操作。
public static void main(String[] commandlineArgument) {
Integer[] array = ReadFile4.readFileReturnIntegers(commandlineArgument[0]);
ReadFile4.printArrayAndIntegerCount(array, commandlineArgument[0]);
}
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) {
// loop through file for integers and store in array
try {
while (inputFile.hasNext()) {
if (inputFile.hasNextInt()) {
array[i] = inputFile.nextInt();
i++;
}
else {
inputFile.next();
}
}
}
finally {
inputFile.close();
}
System.out.println(i);
for (int v = 0; v < i; v++) {
System.out.println(array[v]);
}
}
return array;
}
public static void printArrayAndIntegerCount(Integer[] array, String filename) {
//print number of integers
//print all integers that are stored in array
}
}
然后我将使用第二种方法打印所有内容,但我可以稍后再担心。 :o
文本文件的示例内容:
Name, Number
natto, 3
eggs, 12
shiitake, 1
negi, 1
garlic, 5
umeboshi, 1
样本输出目标:
number of integers in file "groceries.csv" = 6
index = 0, element = 3
index = 1, element = 12
index = 2, element = 1
index = 3, element = 1
index = 4, element = 5
index = 5, element = 1
对于类似的问题,我们深表歉意。我压力很大,甚至更多的是我做错了......我完全被困在这一点上:(
【问题讨论】:
-
您应该再次阅读this 答案。尤其是末尾的
printf。 -
数组的使用是绝对必要的吗?您最好使用
List实现(例如ArrayList):这样您就不必在开始时声明其大小,也不必管理放入其中的项目的索引。 -
不幸的是我必须为这个程序使用一个数组。
标签: java arrays exception file-io