线程“main”java中的indexoutofboundsexception异常。lang.ArrayIndexOutofBounds异常:发电机处为3。main(Generator.java:35)
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.reflect.Array;
import java.util.Scanner;
public class Generator {
public static void main(String[] args) throws FileNotFoundException {
int scorehome = 0;
int scoreaway = 0;
int invalid = 0;
int goals = 0;
int valid = 0;
Scanner scanner = new Scanner(new File("Results.txt")); // create a scanner which scans from a file
String line; // stores the each line of text read from the file
while ( scanner.hasNext() ) {
line = scanner.nextLine(); // read the next line of text from the file
//split the line
String [] elements = line.split(":");
//System.out.println("Element " + (i+1) + " was : " + elements[i]);
if (elements.length < 4) {
String home = elements[0].trim();
String away = elements[1].trim();
String homescore = elements[2].trim();
String awayscore = elements[3].trim();
boolean homescoreVal = false;
boolean awayscoreVal = false;
boolean homenameVal = false;
boolean awaynameVal = false;
try { // "try" is a special statement which allows us to deal with "exceptions"
scorehome = Integer.parseInt(homescore); // attempt to convert the String into an Integer type value
homescoreVal = true;
} catch (NumberFormatException e) {
homescoreVal = false;
}
try {
scoreaway = Integer.parseInt(awayscore); // attempt to convert the String into an Integer type value
awayscoreVal = true;
} catch (NumberFormatException e) {
homescoreVal = false;
}
if (home.length() <= 1) {
homenameVal = false;
} else {
homenameVal = true;
}
if (away.length() <= 1) {
awaynameVal = false;
} else {
awaynameVal = true;
}
if (homescoreVal == true && awayscoreVal == true
&& homenameVal == true && awaynameVal == true){
System.out.println(home + " [" + scorehome + "] | "
+ away + " [" + scoreaway + "]\r");
goals = (scorehome + scoreaway) + goals;
valid = 1 + valid;
} else {
invalid = 1 +invalid;
}
} else {
invalid = 1 + invalid;
}
}
System.out.println("\rValid match was " + valid
+ ", total goals scored was " + goals);
System.out.println("Invalid match count was " + invalid + ".");
System.out.println("\nEOF"); // Output and End Of File message.
}
}
我似乎得到了一个资源泄漏,说我的扫描仪从未关闭,我的import java.lang.reflect.Array;
从未被使用。关于如何解决这两个问题中的任何一个,以及为什么会发生这种情况,有什么想法吗
# 1 楼答案
你可能想要改变
到
因为
elements
数组中至少有4个元素(当您尝试访问elements[3]
)时