猿问

使用 Java 程序获取 ArrayIndexOutOfBounds 错误

我正在制作一个程序,试图根据之前的决定猜测您是要选择正面(h)还是反面(t)。程序在前 3 次猜测“h”,然后查找玩家的最后两个选择,遍历之前的选择以找到相同的决策组合并计算哪个决策(h 或 t)遵循相同组合最多次数,然后根据猜测选择组合。如果它猜对了你的输入,它就赢了,否则玩家就赢了。第一个获得25胜,赢得整场比赛。


该程序对前 3 次猜测工作正常,但当它进入第二个 while 循环时,它给出“线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: -2”


import java.util.ArrayList;

import java.util.Scanner;


public class Guesser {


    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

        ArrayList<String> list = new ArrayList<>();


        int last = (list.size() - 1);

        int secondToLast = (list.size() - 2);


        int index = 2;

        int wins = 0;


        int h = 0;

        int t = 0;


        while (wins < 25 && list.size() - wins < 25) {

            System.out.println("Type h or t: ");

            String letter = reader.nextLine();

            list.add(letter);

            String guess = "h";

当程序进入此文本下方的 while 循环时,它停止工作(程序应该在此处尝试将最后两个决策与之前的所有决策进行比较,以尝试找到相同的决策组合并找出哪个决策(h 或 t)大部分时间遵循组合):


            while (list.size() > 3 && index < list.size()) {


                if (list.get(index - 2).equals(list.get(secondToLast)) 

                    && list.get(index - 1).equals(list.get(last))) {


                    String nextGuess = list.get(index); 

                    if (nextGuess.equals("t")) {

                        t++;

                    } else {

                        h++;

                    }


                }

                index++;


            }

下面的一切都有效:


            if (t > h) {

                    guess = "t";

                } 


            System.out.println("You typed " + letter + ", I guessed " + guess +".");

            if (guess.equals(letter)) {

                wins++;

            } 

            System.out.println("Computer wins: " + wins);

            System.out.println("Player wins: " + (list.size() - wins));

            System.out.println("");

        } 


    }

}


UYOU
浏览 176回答 2
2回答

蝴蝶刀刀

这些行有错误:ArrayList<String> list = new ArrayList<>();// here list is empty and its size is 0int last = (list.size() - 1);// here last is 0 - 1 = -1int secondToLast = (list.size() - 2);// here secondToLast is 0 - 2 = -2将这些行更改为:int last = list.size() - 1 >= 0 ? list.size() - 1 : 0;int secondToLast = list.size() - 2 >= 0 ? list.size() - 2 : 0;改变这一行: while (list.size() > 3 && index < list.size())对此:while (list.size() > 3 && index >= 2 && index < list.size())因此index - 2总是大于或等于零并更改此行: int secondToLast = (list.size() - 2);对此:int secondToLast = list.size() - 2 >= 0 ? list.size() - 2 : 0;

跃然一笑

int last = (list.size() - 1);&nbsp;int secondToLast = (list.size() - 2);将这些放在 while 循环中。它会起作用。:)
随时随地看视频慕课网APP

相关分类

Java
我要回答