这个问题在这里已经有了答案:
什么是indexoutofboundsexception?我该怎么修[重复](1个答案)
两天前关门了。
此错误位于的indexoutofboundsexception中 System.out.println(hurricane.get(2));
. 我怎样才能解决这个问题,以便打印一个飓风对象?我试过几种不同的方法,但都没有用。我试着给hurricane加上null,但没用。它还说索引2超出了长度2的界限。
import java.util.ArrayList;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
import java.util.Scanner;
public class HurricaneTesterTest
{
public static void main(String[] args) throws IOException {
//read data from text file & put in an array
File fileName = new File("HurricaneData.txt");
Scanner inFile = new Scanner(fileName);
int numValues = 0;
//count number of lines in text file
while (inFile.hasNextLine()) {
inFile.nextLine();
numValues++;
}
inFile.close();
//initialize arrays based on lines counted in text file
ArrayList < Integer > years = new ArrayList < Integer > ();
ArrayList < String > months = new ArrayList < String > ();
ArrayList < Integer > pressures = new ArrayList < Integer > ();
ArrayList < Double > windSpeeds = new ArrayList < Double > ();
ArrayList < String > names = new ArrayList < String > ();
ArrayList < String > Cat1 = new ArrayList < String > ();
//read and assign data from text file to the arrays
inFile = new Scanner(fileName);
int index = 0;
while (inFile.hasNext()) {
years.add(inFile.nextInt());
months.add(inFile.next());
pressures.add(inFile.nextInt());
windSpeeds.add(inFile.nextDouble());
names.add(inFile.next());
index++;
}
inFile.close();
for (int i = 0; i < windSpeeds.size(); i++) {
windSpeeds.set(i, windSpeeds.get(i) * 1.151);
//System.out.println(windSpeeds);
}
for (int x = 0; x < windSpeeds.size(); x++) {
if (windSpeeds.get(x) < 96 && windSpeeds.get(x) > 73) {
Cat1.add("Category 1");
}
if (windSpeeds.get(x) < 111 && windSpeeds.get(x) > 95) {
Cat1.add("Category 2");
}
if (windSpeeds.get(x) < 130 && windSpeeds.get(x) > 110) {
Cat1.add("Category 3");
}
if (windSpeeds.get(x) < 157 && windSpeeds.get(x) > 129) {
Cat1.add("Category 4");
}
if (windSpeeds.get(x) > 156) {
Cat1.add("Category 5");
}
}
ArrayList < Hurricane > hurricane = new ArrayList < Hurricane > ();
for (int a = 0; a < hurricane.size(); a++) {
hurricane.add(null);
}
for (int r = 0; r < hurricane.size(); r++) {
hurricane.add(new Hurricane(years.get(r), names.get(r), months.get(r), Cat1.get(r), pressures.get(r), windSpeeds.get(r)));;
}
System.out.println(hurricane.get(2));
}
}
//create a Hurricane ArrayList using the data above
//user prompted for range of years
//print the data
1条答案
按热度按时间ttcibm8c1#
根据这些行,您没有向列表添加任何内容,因为它是空的。请尝试以下操作:
对你来说应该有用。您可能会遇到cat1的问题,因为它看起来像是块具有错误的范围比较:cat1(73-96),cat2(95-111)-重叠。