【发布时间】:2016-01-06 04:00:55
【问题描述】:
我收到此错误:
线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常:2
在 JavaProject.main(JavaProject.java:70)
代码如下:
try
{
PrintWriter writer = new PrintWriter("Gamer Report Data.txt");
writer.println("Player: " + gamerName);
writer.println();
writer.println("-------------------------------");
String[] report = gamerReport.split(gamerReport, ':');
writer.println("Game:" + ", score=" + report[1] + ", minutes played=" + report[2] + report[3]);
writer.close();
} catch (IOException e)
{
System.err.println("File does not exist!");
}
我认为它与我的 for 循环有关,但我没有运气改变它。
import java.util.Scanner;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.io.PrintWriter;
public class JavaProject {
private static char[] input;
@SuppressWarnings("null")
public static void main(String[] args) {
for (int b = 1; b < 100; b++) {
// this is making the code loop 100 times
int hrs, mins;
int[] gameCount;
int[] minutesPlayed = new int[100];
String gamerName, gamerReport;
// Main data storage arrays
String[] gameNames = new String[100];
int[] highScores = new int[100];
Scanner Scan = new Scanner(System.in);
// formatting for output and input
System.out.println("////// Game Score Report Generator \\\\\\\\\\\\");
System.out.println(" ");
// user enters name and then moves to next line
System.out.println("Enter Your Name");
gamerName = Scan.nextLine();
// user is given an example of input format
System.out.println("Input Gamer Information " + "Using Format --> Game : Achievement Score : Minutes Played");
System.out.println(" ");
System.out.println("Game : Achievement Score : Minutes Played");
gamerReport = Scan.nextLine();
String[] splitUpReport; // an array of string
splitUpReport = gamerReport.split(":"); // split the text up on the colon
int i = 0;
// copy data from split text into main data storage arrays
gameNames[i] = splitUpReport[0];
highScores[i] = Integer.parseInt(splitUpReport[1].trim());
minutesPlayed[i] = Integer.parseInt(splitUpReport[2].trim());
// output to file
try
{
PrintWriter writer = new PrintWriter("Gamer Report Data.txt");
writer.println("Player: " + gamerName);
writer.println();
writer.println("-------------------------------");
String[] report = gamerReport.split(gamerReport, ':');
writer.println("Game:" + ", score=" + report[1] + ", minutes played=" + report[2] + report[3]);
writer.close();
} catch (IOException e)
{
System.err.println("File does not exist!");
}
}
}
public static char[] getInput() {
return input;
}
public static void setInput(char[] input) {
JavaProject.input = input;
}
}
【问题讨论】:
-
错误很可能来自
report[]数组。不幸的是,您省略了定义/分配字符串gamerReport的代码,因此我们无法确定问题所在。 -
对其进行了编辑以包含完整代码
-
您在控制台中为
gamerReport输入了什么值?如果它没有至少两个冒号(标点符号,不是人体器官),那么您将得到您所看到的ArrayIndexOutOfBoundsException。 -
我正在按预期输入数据i.gyazo.com/b97e1c332ef4a31a669022cf5c54fab8.png 没有人类冒号
标签: java arrays for-loop printwriter