我应该从文件中读取单词搜索难题,我的问题我一直都越界错误。我不知道如何正确地将单词拼图的格式设置为文件的规范。拼图的格式通常是这样的:5 5 devol redph qchzj poaaf vammn qtfox
到目前为止,这是我的工作,我觉得我已经从文件中读取了下来,但是将其转换为单词搜索难题。特别是不要硬编码单词Seaarch Puzzle的行和列的规范。
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!
解决此问题后,您将遇到更多问题-您的代码没有按照您想的那样执行操作,但是这些都是单独的问题,应单独发布。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。