[英]Reading text File and putting it in a array
我正在尝试从文本文件中获取一组25个数字并将其转换为数组。 但是我迷路了。
我读过其他一些与此类似的问题,但是所有问题都使用了导入和其他功能,除了import java.io. *,我不想使用任何导入。 也没有任何清单。 另外,这个方法中的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)抛出IOException,FileNotFoundException {int [] array = processFile(“ C:\\ Users \\ griff_000 \\ Desktop \\ TestWeek13.txt”); printArray(array); }
您的错误是在a[intValue]++;
。 您要告诉Java在[intValue]处找到该元素,并将其添加为当前值1。 从您的问题中,我了解到您想将intValue作为数组元素。
由于您将i
用作迭代器,因此只需添加以下元素即可:
a[i] = intValue;
您在这里做什么:
a[intValue]++;
正在将读取值的数组位置增加一。 如果读取的数字是2000,则您正在增加[2000]
你可能想这样做
a[i]=intValue;
我不清楚您的整个import
限制,为什么您正试图限制进口数量?
无论如何,看着您的代码,似乎数组的概念还不清楚。
使用以下语法访问数组:
array[index] = value;
查看您的代码,一行a[intValue]++;
实际上是在查找数组索引intValue
(从文件中读取的数字)并将其递增1。 这不仅不是您想要的,而且数组长度上的数字将导致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;
}
请注意,在此上下文中使用了附加变量i
来简化用于访问数组的递增索引号。 如果仔细检查此方法,则长度超过25个元素的输入文件也会由于变量i
变为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循环如何将iterator变量集成到优美的一行中,从而使其余代码保持整洁和可读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.