gpt4 book ai didi

java - 向数组和 switch 语句添加元素时出现问题,并出现错误 ArrayIndexOutOfBoundsException

转载 作者:行者123 更新时间:2023-12-01 16:44:52 25 4
gpt4 key购买 nike

下面是我正在编写的一个程序的开头,该程序用于从weather.txt读取温度信息,该程序以以下格式列出日期和温度数据:01/01/1941 38 25并表示日期、最低温度和最高温度。 Weather.txt 中的第一个条目是数据条目总数,接下来的 3 行用于格式化:

import java.io.*;
import java.util.*;

public class WeatherAnalysis {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("weather.txt"));
input.useDelimiter("[/ \t\n\r]+");

int tempCount = input.nextInt();
int[] month = {tempCount};
int[] day = {tempCount};
int[] year = {tempCount};
int[] tmax = {tempCount};
int[] tmin = {tempCount};

System.out.println("There are " + tempCount + " entries.");
for (int i = 0; i < 3; i++) {
input.nextLine();
}
int count = 0;
for (int i = 0; i <= tempCount; i++) {
if (count < 5) {
switch(count) {
case 0:
month[i]=input.nextInt();
break;
case 1:
day[i]=input.nextInt();
break;
case 2:
year[i]=input.nextInt();
break;
case 3:
tmax[i]=input.nextInt();
break;
case 4:
tmin[i]=input.nextInt();
break;
}
count++;
}
else {
count = 0;
}


}
}
}

我已经初始化了 5 个整数数组。由于数据是静态格式化的,所以我打算通过固定的格式来读取每条数据。为此,我创建了一个带有计数器的 switch 语句。

我的想法是,count 变量将找到相应的情况,将元素添加到数组中,中断并在获取下一个输入之前递增计数器。使用 Eclipse 的调试器,我可以看到我的 icount 变量正确递增。

但是,一旦调试器读取 day[i]=input.nextInt(); 我就会遇到...

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at WeatherAnalysis.main(WeatherAnalysis.java:29)

诚然,我在掌握数组方面有点困难。我知道我的初始化不好。对于初学者来说,它们太高了(有 30k 数据条目),但我犹豫是否将其设置为任意值,因为担心它太小。

此外...使用这种方法,我想如果我打印出我的数组,我将会有很多随机跳转。我相信元素最初设置为 0,所以我的想法是我的数组最终可能会像 0,0,0,46,0,0,0,42 等。

任何见解都将非常感激。这是我的第二篇文章,请原谅任何格式,谢谢!!

最佳答案

当你这样做时:

int[] month = {tempCount};

这将创建一个仅包含一个元素 tempCountArray。您想要:

int[] month = new int[tempCount];

这将创建一个大小 tempCountArray

<小时/>

另请注意此循环:

for (int i = 0; i < 3; i++) {
input.nextLine();
}

正在调用nextLine(),但没有将其解析为任何内容。

I believe elements are inititally set to 0, so my thoughts are that my arrays may end up like 0,0,0,46,0,0,0,42 etc..

是的,这是正确的,因为您始终将其设置为 i,每当您添加到任何 Array 时,它都会递增。我建议使用List,这样您就可以简单地使用add() 方法并将其添加到List 的末尾。另外ArrayList没有固定的大小,因此您不必事先声明大小。

关于java - 向数组和 switch 语句添加元素时出现问题,并出现错误 ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53753613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com