我正试图从一个文本文件中提取一组25个数字,并将其转换为数组。但我迷路了。
我读过其他一些类似的问题,但它们都使用了导入和附加,除了导入java.io.*之外,我不想使用任何导入;也没有任何列表。此外,这个is方法中的for循环就是我把它搞砸了,因为我搞不清楚。
public static int[] processFile (String filename) throws IOException, FileNotFoundException {
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)));
String line;
int[] a = new int[25];
while (( line = inputReader.readLine()) != null){
int intValue = Integer.parseInt(line); //converts string into int
for (int i = 0; i < a.length; i++){
a[intValue]++;
}
}
return a;
}
public static void printArray (int[] a) {
for (int i = 0; i<a.length; i++) {
System.out.println (a[i]);
}
}public static void main(String[]args)throws IOException,FileNotFoundException{int[]array=processFile("C:\Users\griff_000\Desktop\TestWeek13.txt");printArray(数组);}
我不清楚你的整个import
限制,你为什么要限制进口数量?
不管怎样,看看你的代码,数组的概念似乎并不那么清晰。
数组的访问语法为:
array[index] = value;
查看您的代码,行a[intValue]++;
实际上是找到数组索引intValue
(从文件中读取的数字)并将其递增一。这不仅不是您想要的,超过数组长度的数字将导致ArrayIndexOutOfBoundsException
。
作出上述修正我们得到:
public static int[] processFile (String filename) throws IOException, FileNotFoundException{
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)));
String line;
int[] a = new int[25];
int i = 0; // We need to maintain our own iterator when using a while loop
while((line = inputReader.readLine()) != null){
int intValue = Integer.parseInt(line); //converts string into int
a[i] = intValue; // Store intValue into the array at index i
i++; // Increment i
}
return a;
}
请注意,在此上下文中使用附加变量CCD_ 5来促进用于访问数组的递增索引号。如果仔细检查此方法,由于变量i
变为25
(超出数组的限制),长度超过25个元素的输入文件也会抛出ArrayIndexOutOfBoundsException
。为了解决这个问题,我建议将循环结构更改为for循环(假设您的输入数组是固定大小的),如下所示:
public static int[] processFile (String filename) throws IOException, FileNotFoundException{
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)));
String line;
int[] a = new int[25];
for(int i = 0; i < a.length; i++){
String line = inputReader.readLine(); // Move the readline code inside the loop
if(line == null){
// We hit EOF before we read 25 numbers, deal appropriately
}else{
a[i] = Integer.parseInt(line);
}
}
return a;
}
注意for循环是如何将迭代器变量集成到一行漂亮优雅的代码中的,从而保持代码的其余部分整洁可读。
您的错误在a[intValue]++;
行。您告诉Java在[intValue]中找到元素,并在其当前值上加1。从您的问题中,我了解到您希望将intValue作为数组元素。
由于您使用i
作为迭代器,要添加元素,只需使用:
a[i] = intValue;
您在这里做的事情:
a[intValue]++;
正在将读取值的数组位置增加一。如果读取的数字是2000,则增加[2000]
你可能想做这个
a[i]=intValue;