【问题标题】:Exception : java.lang.ArrayIndexOutOfBoundsException异常:java.lang.ArrayIndexOutOfBoundsException
【发布时间】: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


【解决方案1】:

你的代码有两个问题:

1)

String[] report = gamerReport.split(gamerReport, ':');

应该是

String[] report = gamerReport.split(":");

就像你对splitUpReport 所做的那样(不确定你为什么要再次分裂)。

2) 数组是零索引的,所以 print 语句应该是这样的:

writer.println("Game:" + ", score=" +report[0] +", minutes played="+ report[1] + report[2]);

【讨论】:

  • 很好地了解数组索引。
  • @BrandonParkinson 您需要将字符串传递给split() 方法:":",而不是':'
  • 实际上,String.split() 有一个重载版本,它以正则表达式作为第一个参数,int 限制作为第二个参数。巧合的是,他的代码编译并运行,但并不像预期的那样。
  • 所以你是说我的代码在技术上不应该运行?
  • @BrandonParkinson,它运行是因为您将 gamerReport 作为正则表达式字符串传递,char (':') 作为 int 传递。要么是怪异的事故,要么是不幸的猜测。
【解决方案2】:

您的代码中的错误是由try 块中的此代码引起的:

String[] report = gamerReport.split(gamerReport, ':');

您实际上是在尝试将gamerReport 字符串用作正则表达式,使用limit58,这是冒号的数值。

此拆分的结果是 2 个空的 String 元素,它们对应于发生在 beforeafter 正则表达式(即字符串本身)的匹配。 p>

ArrayIndexOutOfBounds 异常发生在您尝试访问此数组的第三个元素时:

要解决您的问题,只需按如下方式定义 report 数组:

String[] report = gamerReport.split(':');

正如@shmosel 指出的那样,您可能还想在此处更改数组索引:

writer.println("Game:" + ", score=" + report[0] +", minutes played="+ report[1] + report[2]);

【讨论】:

  • 感谢您的详细回复非常有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-19
  • 2015-02-27
  • 1970-01-01
  • 2018-06-22
  • 2013-10-02
  • 2012-01-13
相关资源
最近更新 更多