我在WeatherAnalysis.main(WeatherAnalysis.java:37)得到一个“线程中的异常”主“java.lang.ArrayIndexOutOfBoundsException:5”“我不确定第37行有什么问题,date [CurrentLine] [0 ] =(int)fullDate%100;。尝试使用.txt文件输出1941年至2013年的天气模式。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WeatherAnalysis {
public static void main(String[] args) throws FileNotFoundException {
int NumberOfDays = 0;
String station;
File f = new File("PortlandWeatherCut.txt"); //Import text file.
Scanner input= new Scanner(f);
input.nextLine();
input.nextLine();
while (input.hasNextLine()) { //Assign number of days to be
NumberOfDays++;
input.nextLine();
}
double[][] date = new double[NumberOfDays][3];
double[] prcp = new double[NumberOfDays];
double[] snow = new double[NumberOfDays];
double[] snwd = new double[NumberOfDays];
double[] tmax = new double[NumberOfDays];
double[] tmin = new double[NumberOfDays];
int CurrentLine = 0;
double fullDate = 0.0;
File g = new File("PortlandWeather.txt"); //Import text file.
Scanner weather= new Scanner(g);
weather.nextLine(); weather.nextLine();
while(weather.hasNextLine()) { //variables and converts to inches.
station = weather.next();
fullDate = weather.nextDouble();
date[CurrentLine][0] = (int)fullDate % 100;
date[CurrentLine][1] = ((int)fullDate % 10000) / 100;
date[CurrentLine][2] = (int)fullDate / 10000;
prcp[CurrentLine] = weather.nextDouble()* .00393701;
snow[CurrentLine] = weather.nextDouble()* 0.0393701;
snwd[CurrentLine] = weather.nextDouble()* 0.0393701;
tmax[CurrentLine] = (weather.nextDouble() / 10.0) * (9.0/5.0) + 32.0;
tmin[CurrentLine] = (weather.nextDouble() / 10.0) * (9.0/5.0) + 32.0;
CurrentLine++;
weather.nextLine();
}
int indexPoint = 0;
int nextPoint = 1;
int endPoint = 0;
for (int x = 1; x < date.length; x++){
//loop that calculates array section to be averaged,
//uses a method to average them, then prints a table
do {
nextPoint++;
endPoint++;
}
while(((int)date[nextPoint - 1][02] / 10) == ((int)date[nextPoint][1] / 10));
if ( nextPoint < date.length) {
System.out.printf("%4.0f's Average Max Temp = %4.1f\tAverage Min Temp = %4.1f\n",
date[indexPoint][02],arrayAvg(tmax, indexPoint, endPoint),
arrayAvg(tmin, indexPoint, endPoint));
indexPoint = nextPoint;
} else
System.out.println();
}
}
public static double arrayAvg(double a[], int fromIndex, int toIndex) {
//Averages the values between the entered parameters and returns it.
double sum = 0;
double divisor = 0;
for (int i = fromIndex; i < toIndex; i++){
if (a[i] == 393.6616299) {
divisor++;
} else {
sum += a[i];
divisor++;
}
}
double average = sum / divisor;
return average;
}
}
答案 0 :(得分:0)
好像你的问题在第37行。我认为那是
date[currentline][0] = (int)fullDate%100
在你的while循环中。循环继续在创建日期二维数组的NumberOFdAYS之上,因此它抛出了回合。
我的第一个建议是将这个怪物功能分解为更小的功能(查找单一责任原则)。
我的第二个建议是做TDD(测试驱动开发)
但是如果你想要一个快速而又脏的调试,请在while循环开始时执行以下操作:
System.out.printf("Current line = %d, does weather has next line? = %b", CurrentLine, weather.hasNextLine)
这将显示异常之前currentLine的所有值,并显示布尔值。