簡體   English   中英

使用 Puzzle 並弄清楚如何修復越界錯誤

[英]Working With Puzzle and figuring how to fix out of bound error

我的錯誤說明
我應該從文件中讀取單詞搜索拼圖我的問題我一直在越界錯誤。 我不知道如何根據文件的規范正確地設置單詞拼圖的格式。 拼圖的格式通常是這樣的:5 5
轉移
紅衛兵
知乎
農夫
瓦姆恩
qtfox

到目前為止,這是我的工作,我覺得我已經從文件中讀取,但將其轉換為單詞搜索拼圖。 特別是盡量不對單詞搜索拼圖的行和列的規范進行硬編碼。

public static char[][] fill(){
    // Created 2 different scanner one for user input and one to read the file

    Scanner file1 = new Scanner(System.in);
    // created a count to add the keywords
    int count = 0;

    //System.out.print("Please enter a keyword to search for.");
    // Asking user to input a valid file name
    System.out.print("Please enter a valid puzzle file name\nYou will be asked for the same file name again later.");
    String wordFile = file1.nextLine();
    FileReader infile;
    boolean validFile = false;
    // Creating a while loop that will keep asking for a valid file name
    while(!validFile) {
        // Using a try and catch to obtain correct file
        try {
            infile = new FileReader(wordFile);
            file1 = new Scanner(infile);
            validFile = true;
        }
        //ask the user to put a valid file name if they are wrong
        catch(IOException e) {
            System.out.println("Not a valid file name, please enter again!");
            wordFile = file1.nextLine();
        }
    }
    String numbers = file1.nextLine();
    String[] fileArray = numbers.trim().split(" ");

    int rows = Integer.parseInt(fileArray[0]);
    int columns = Integer.parseInt(fileArray[1]);

    char[][] fillThemLetters = new char [rows][columns];


    String letters = file1.nextLine().trim().replace(" ", "");

    char [] condensed =  letters.toCharArray(); 

    for (int i = 0; i < condensed.length; i++) {

        for(int row = 0; row < rows; row++){


            for(int column = 0; column < columns; column++)
            {
                char index = condensed[i];
                fillThemLetters[row][column] = index;
                i++;
            }
        }

    }   
    return fillThemLetters;
}

您的索引越界錯誤是由此處引起的:

for(int column = 0; column < columns; column++)
{
    char index = condensed[i];
    fillThemLetters[row][column] = index;
    i++; // <--------- THIS IS WRONG!!!
}

看到i++嗎? 您無緣無故地從最外層循環增加計數器。 讓循環處理它自己的增量,它已經內置了,像這樣:

for (int i = 0; i < condensed.length; i++) {  // <--- You already have i++ here!

解決這個問題后,您將遇到更多問題——您的代碼沒有按照您認為的那樣做,但這些都是單獨的問題,應該單獨發布。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM