亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 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 關注
  • 199 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號