尝试从 ArrayList 获取字符串时出现 IndexOutOfBoundsException

所以我正在尝试创建一个小型刽子手迷你游戏。不幸的是,我一直收到同样的错误。我已经尝试重做两次游戏,但似乎仍然无法正确完成。我敢肯定这只是一些逻辑错误或其他什么。


我对 Java 还是比较陌生,所以任何帮助将不胜感激。


我已将程序分成三个类。一种用于 Hangman 对象,一种用于包含所述对象的数组,另一种用于使用这些对象的数组。以下三部分是游戏的片段。


第一类:刽子手


package hangman2;


import java.util.*;

import java.io.*;


public class Hangman {


    private ArrayList<String> words = new ArrayList<>();

    private int diff;


    public Hangman(String fileName, int difficulty) {


        diff = difficulty;

        //easy = 0; medium = 1; hard = 2


        try {

            Scanner scanFile  = new Scanner(new File(fileName));


            while(scanFile.hasNext()) {


                String line = scanFile.nextLine();

                Scanner scanLine = new Scanner(line);

                String tempWord = scanLine.next();


                words.add(tempWord);

            }

        }

        catch (FileNotFoundException e) {

            System.out.println("File not found\n" + e);

        }

    }


    //Gets

    public ArrayList<String> getWords() { return words; }

    public int getDifficulty() { return diff; }


    //Sets

    public void addWord(String word) { words.add(word); }

}


潇湘沐
浏览 251回答 1
1回答

Helenr

您应该检查是否max为 0,如果是,则返回null或空字符串,然后处理这种特殊情况。我使用Random.nextInt()而不是int randIndex = (int) (Math.random() * max);返回一个伪随机、均匀分布的 int 值,介于 0(含)和指定值(不含)之间,从该随机数生成器的序列中提取。nextInt 的一般约定是伪随机生成并返回指定范围内的一个 int 值。所有绑定可能的 int 值都以(大约)相等的概率产生请记住,最后一个元素的索引是 size()-1public String getRandomWord() {&nbsp; &nbsp; Hangman workingHangman = chooseDifficulty();&nbsp; &nbsp; int max = workingHangman.getWords().size();&nbsp; &nbsp; if (max == 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return "";&nbsp; &nbsp; }&nbsp; &nbsp; int randIndex = new Random().nextInt(max); // returns an integer between 0 and max-1&nbsp; &nbsp; return workingHangman.getWords().get(randIndex);}&nbsp;&nbsp;您还应该使用try-with-resources来确保您正在使用的资源在您完成后关闭。public Hangman(String fileName, int difficulty) {&nbsp; &nbsp; diff = difficulty;&nbsp; &nbsp; //easy = 0; medium = 1; hard = 2&nbsp; &nbsp; try (Scanner scanFile&nbsp; = new Scanner(new File(fileName))) {&nbsp; &nbsp; &nbsp; &nbsp; while(scanFile.hasNext()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String line = scanFile.nextLine();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Scanner scanLine = new Scanner(line);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String tempWord = scanLine.next();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; words.add(tempWord);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; catch (FileNotFoundException e) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("File not found\n" + e);&nbsp; &nbsp; }}最后,我建议使用调试器来了解您在每个 Hangman 中放入的内容。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java