我已经做了一段时间的单词搜索程序了。它接受一个文本文件作为输入,例如:
7 //number of rows
15 // number of columns
mucatpoltqfegkq
hfytpnsdlhcorey
pgrhdqsypyscped
gkagdntorioapje
yerjodxnqzztfmf
hypmmgoronkzhuo
qrtzaulhtgtqaao然后查找用户输入的单词。文件读取和数组创建在一个单独的类中进行。
现在,我需要让它找到水平从左到右,向下,对角从左上方到右下角的单词。我要做的是先找出第一个字母出现的位置,然后从这个位置开始计算单词的其余部分。
到现在为止,我所做的只是偶尔起作用。我能够在第一行垂直地找到"cat“,但是当我试图在对角线上找到比萨饼时,我会得到一个超出界限的错误。我知道这意味着有些东西超出了数组,我知道如何在更简单的程序中修复它(就像需要遍历数组的for-循环),但这里不行。
我还没有开始使用checkDown方法,因为我想解决我现在已经解决的问题。这是我的密码:
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;
for (int row = 0; row < inArray.length; row++)
{
for (int col = 0; col < inArray[row].length; col++)
{
System.out.print(inArray[row][col]);
}
System.out.println();
}
System.out.println();
}
public void play()
{
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);
}
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();
}
}
System.out.println();
}
}
public void suspectAnalysis()
{
checkRight();
checkDown();
checkDiagonal();
}
public void checkRight()
{
for(int i = 1; i < (targetWord.length()); i++)
{
if(array[rowLocation][colLocation + i] == targetWord.charAt(i))
{
System.out.println(targetWord + " found horizontally at row " + rowLocation + " and column " + colLocation);
}
}
}
public void checkDown()
{
//code goes here
}
public void checkDiagonal()
{
for(int i = 1; i < (targetWord.length()); i++)
{
if(array[rowLocation + i][colLocation + i] == targetWord.charAt(i))
{
System.out.println(targetWord + " found diagonally at row " + rowLocation + " and column " + colLocation);
}
}
}
}我很感谢你的帮助。谢谢!
发布于 2016-11-11 05:26:09
您的checkDiagonal()方法是outOfBounds,因为您没有添加一个条件来检查您的[rowLocation+i]和[colLocation+i]是否在数组的界限内。加上这个条件,你就可以走了。
发布于 2016-11-11 05:27:57
上面的评论说:if(array[rowLocation][colLocation + i] == targetWord.charAt(i))看起来很可疑。
如果你的单词沿着网格的右边垂直排列,会发生什么?您应该考虑在该语句之前添加一个if语句,以检查[rowLocation + i][colLocation + i]是否在界限之内。如果没有,您可以确保单词没有以这种方式对齐(无论是在您的checkRight()或checkDiagonal()函数中),并且您可以退出循环并从函数返回以检查另一个方向。
https://stackoverflow.com/questions/40541492
复制相似问题