StringIndexOutOfBoundsException的问题

时间:2014-10-24 11:49:19

标签: java

我必须创建一个数字记忆游戏,但如果用户输入错误的数字,我会得到StringIndexOutOfBoundsException。我看了很多例子,但仍然无法弄清楚如何修复它。这种情况发生在actionPerformed方法中,使用此行代码newNumber = answer.substring(counterOne, counterTwo);非常感谢任何帮助。

import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;



public class MemoryGame extends Applet implements ActionListener, Runnable {

    private Label prompt;
    private Button button;
    private TextField input, numDisplay;
    private int arrayCounter = 3, backgroundColor =0; 
    private int[] myArray = new int[arrayCounter];
    private int[] compare = new int[arrayCounter];
    private Thread delayThread;
    private boolean running = true, isCompare; 


    public void init(){
        prompt = new Label("Enter the numbers!");
        input = new TextField(20);
        numDisplay = new TextField(20);
        numDisplay.setEditable(false);
        button = new Button("Enter");

        add(prompt);
        add(input);
        add(numDisplay);
        add(button);
        button.addActionListener(this);

        populateArray();
        delayThread = new Thread(this); 
        delayThread.start();


    }
    public void paint(Graphics g){

        if(backgroundColor == 1){
            setBackground (Color.green);
        }
        else if(backgroundColor == 2){
            setBackground (Color.red);
        }
    }


    public void populateArray() {
        GenerateNumbers a = new GenerateNumbers();
        myArray = a.returnArray(); 


        int count = 1;
        for(int i = 0; i < myArray.length;i++){
            System.out.println("index: " + count + " : " + myArray[i]);
            count++;
            numDisplay.setText(" ");
        } //for testing purpose
    }

    @Override
    public void actionPerformed(ActionEvent e)throws StringIndexOutOfBoundsException {
        String answer ="", newNumber="";
        String[] stringArray = new String[arrayCounter];
        int counterOne = 0, counterTwo = 2;
        try{
            answer = input.getText();
            for(int i = 0; i < arrayCounter;i++){
                newNumber = answer.substring(counterOne, counterTwo);
                stringArray[i] = newNumber;
                counterOne += 3;
                counterTwo += 3;
            }
        }catch(NumberFormatException ex){
            ex.printStackTrace();
        }

        for(int i = 0; i < arrayCounter;i++){
            compare[i] = Integer.parseInt(stringArray[i]);
        }

        for(int i = 0; i < arrayCounter;i++){
            if(myArray[i] != compare[i]){
                backgroundColor = 2;
                input.setText("Wrong");
                repaint();
            }
            else{
                backgroundColor =1;
                input.setText("RIGHT!");//testing
                repaint();
            }

        }

    }

    public void destroy(){
        running = false; 
    }

    @Override
    public void run() {
        while(running){
            String numberString = "" ,stringTwo = "  ";
            for(int i = 0; i < arrayCounter;i++){
                numberString += myArray[i] + stringTwo;
                numDisplay.setText(numberString);
            }
            try{
                delayThread.sleep(3500);
            }catch(InterruptedException e){
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }
            numDisplay.setText(" ");
            destroy();
        }
    }

}

2 个答案:

答案 0 :(得分:2)

在致电answer.substring(counterOne, counterTwo)之前,您必须确保0 <= counterOne < answer.length()counterTwo <= answer.length()

substring如果IndexOutOfBoundsException,则会the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex

编辑:

让我们试着解决你的问题。以下循环的逻辑是有缺陷的:

        answer = input.getText();
        for(int i = 0; i < arrayCounter;i++){
            newNumber = answer.substring(counterOne, counterTwo);
            stringArray[i] = newNumber;
            counterOne += 3;
            counterTwo += 3;
        }

如果我理解你要做什么,你期望输入字符串(存储为answer)包含数字,你创建这些数字的数组,并将它与正确数字的数组进行比较

但是,上述循环只有在用户的答案以“11x22x33 ...”开头时才会起作用,因为您希望从该输入字符串中提取每个2个字符的arrayCounter(= 3)个子字符串,你是从字符串的位置(0,1)(3,4)(6,7)中提取它们。这意味着如果String短于8个字符,您将获得StringIndexOutOfBoundsException

您不应该对数字的长度或输入字符串中的数字数量进行假设。一个更好,更简单的解决方案是:

stringArray = answer.split(" ");

这会将输入数组拆分为空格。请注意,您将获得的数组长度不一定与正确答案的长度匹配,因此您必须比较长度。

答案 1 :(得分:0)

如果符合以下任何条件,

IndexOutOfBoundsException将会出现

`counterOne` is negative, or 
`counterTwo` is larger than the length of `answer`, or 
`counterOne` is larger than `counterTwo`.

在执行answer.substring(counterOne, counterTwo)之前,您可以执行以下操作

if (counterOne >= 0 && counterTwo < answer.length && counterOne <= counterTwo)