为了账号安全,请及时绑定邮箱和手机立即绑定

使用 Java 程序获取 ArrayIndexOutOfBounds 错误

使用 Java 程序获取 ArrayIndexOutOfBounds 错误

UYOU 2021-06-17 15:15:43
我正在制作一个程序,试图根据之前的决定猜测您是要选择正面(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("");        }     }}
查看完整描述

2 回答

?
蝴蝶刀刀

TA贡献1801条经验 获得超8个赞

这些行有错误:


ArrayList<String> list = new ArrayList<>();// here list is empty and its size is 0


int last = (list.size() - 1);// here last is 0 - 1 = -1

int 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;


查看完整回答
反对 回复 2021-06-17
?
跃然一笑

TA贡献1826条经验 获得超6个赞

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

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

将这些放在 while 循环中。它会起作用。:)


查看完整回答
反对 回复 2021-06-17
  • 2 回答
  • 0 关注
  • 175 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号