【发布时间】:2016-11-13 23:03:04
【问题描述】:
这是一个单词搜索程序。它搜索的文本被输入并转换为另一个类中的二维数组。
这是程序正在搜索的文本:
10 //rows
15 //columns
fqexfecmxdvjlgu
cxomfslieyitqtz
nucatfakuxofegk
hfytpnsdlhcorey
pgrhdqsypyscped
ckadhyudtioapje
yerjodxnqzztfmf
hypmmgoronkzhuo
hdskymmpkzokaao
amuewqvtmrlglad
出于某种原因,即使输入了我的终止字符串end,它也总是会进入我的checkDown() 方法并产生越界错误。如果我注释掉该方法并只执行checkRight() 和checkDiagonal() 方法,一切似乎都正常。
这是我的代码:
import java.util.Scanner;
public class WordSearch
{
private char[][] array;
private String targetWord;
private int rowLocation;
private int colLocation;
public WordSearch(char[][] inArray)
{
array = inArray;
}
public void play()
{
do{
for (int row = 0; row < array.length; row++)
{
for (int col = 0; col < array[row].length; col++)
{
System.out.print(array[row][col]);
}
System.out.println();
}
System.out.println();
Scanner input = new Scanner(System.in);
System.out.println("What word would you like to search for? Type end to quit: ");
targetWord = input.nextLine();
System.out.println("Typed in: " + targetWord);
System.out.println();
compareFirst(targetWord);
} while (!targetWord.equals("end"));
}
public void compareFirst(String inWord)
{
for (int row = 0; row < array.length; row++)
{
for (int col = 0; col < array[row].length; col++)
{
if(array[row][col] == inWord.charAt(0))
{
rowLocation = row;
colLocation = col;
suspectAnalysis();
}
}
}
}
public void suspectAnalysis()
{
checkRight();
checkDown();
checkDiagonal();
}
public void checkRight()
{
for(int i = 1; i < (targetWord.length()); i++)
{
if(colLocation + i > array[0].length - 1)
{
return;
}
else if(array[rowLocation][colLocation + i] != targetWord.charAt(i))
{
return;
}
}
System.out.println(targetWord + " found horizontally at row " + rowLocation + " and column " + colLocation);
System.out.println();
return;
}
public void checkDown()
{
for(int i = 1; i < (targetWord.length()); i++)
{
if(rowLocation + i > array.length - 1 && colLocation + i > array[0].length - 1)
{
return;
}
else if(array[rowLocation + i][colLocation] != targetWord.charAt(i))
{
return;
}
}
System.out.println(targetWord + " found vertically at row " + rowLocation + " and column " + colLocation);
System.out.println();
}
public void checkDiagonal()
{
for(int i = 1; i < (targetWord.length()); i++)
{
if(colLocation + i > array[0].length - 1 || rowLocation + i > array.length - 1)
{
return;
}
else if(array[rowLocation + i][colLocation + i] != targetWord.charAt(i))
{
return;
}
}
System.out.println(targetWord + " found diagonally at row " + rowLocation + " and column " + colLocation);
System.out.println();
}
}
当我注释掉checkDown() 方法时,为什么不会发生这种情况?我该如何解决?
如果有任何帮助,我将不胜感激。谢谢!
【问题讨论】:
-
检查使索引超出范围异常的语句。这种异常并不难理解和修复!
-
@Bluasul 你能添加你用来测试你的 WordSearch 的代码吗,你的 WordSearch 构造函数的示例参数是什么?
-
您的问题是否简单到知道
do...while循环将始终在测试while表达式中的条件之前执行循环体?也就是说,您真的是要使用while循环(在决定是否执行循环体之前测试条件)? -
@alainlompo 它从文件中读取数据,我将其添加到我的问题中
标签: java loops multidimensional-array do-while