Java 读取文本文件并将其放入数组
我试图从文本文件中获取一组25个数字,并将其转换为数组。但是我迷路了 我读过一些与此类似的其他问题,但它们都使用了导入和附加,我不想使用除导入java.io之外的任何导入。*;也没有任何清单。 另外,这个is方法中的for循环是我在搞乱它,因为我无法理解它Java 读取文本文件并将其放入数组,java,arrays,Java,Arrays,我试图从文本文件中获取一组25个数字,并将其转换为数组。但是我迷路了 我读过一些与此类似的其他问题,但它们都使用了导入和附加,我不想使用除导入java.io之外的任何导入。*;也没有任何清单。 另外,这个is方法中的for循环是我在搞乱它,因为我无法理解它 public static int[] processFile (String filename) throws IOException, FileNotFoundException { BufferedReader inputRea
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 mainString[]args引发IOException、FileNotFoundException{
int[]array=processFileC:\Users\griff\u 000\Desktop\TestWeek13.txt;
打印阵列;
}您的错误在a行[intValue]++;。您告诉Java在[intValue]处查找元素,并将1添加到其当前值。从您的问题中,我了解到您希望将intValue作为数组元素 由于您使用i作为迭代器,要添加元素,只需使用:
a[i] = intValue;
你在这里做什么:
a[intValue]++;
正在将读取值的数组位置增加1。如果读取的数字为2000,则表示增加了[2000]
你可能想这样做
a[i]=intValue;
我不清楚你们的整个进口限制,为什么你们要限制你们的进口数量 无论如何,看看你的代码,你似乎对数组的概念不是很清楚 可以使用以下语法访问数组:
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个元素的输入文件也会抛出ArrayIndexOutOfBoundsException,因为变量i变为25超出了数组的限制。要修复此问题,我建议将循环结构更改为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循环是如何将迭代器变量集成到一条优美的线条中的,保持代码的其余部分整洁易读。你能给我们一个你正在阅读的文本文件的例子吗?每一行5 14 3 80 7 45 14 90 66 45 13 32 9 10 54 2 76 5 89 43 6 16 54 63 79我试过了,它只输出我文本文件79中的最后一个数字。我的其他打印方法现在有问题。是吗?好的,非常感谢!还有数组[索引]=值;帮助我以不同的方式思考,好交易:。