【发布时间】:2016-11-11 05:10:12
【问题描述】:
我一直在研究一个单词搜索程序。它需要一个文本文件作为输入,例如:
7 //number of rows
15 // number of columns
mucatpoltqfegkq
hfytpnsdlhcorey
pgrhdqsypyscped
gkagdntorioapje
yerjodxnqzztfmf
hypmmgoronkzhuo
qrtzaulhtgtqaao
然后查找用户输入的单词。文件读取和数组创建发生在一个单独的类中。
现在,我需要让它从左到右、向下、从左上角到右下角水平地找到单词。我要做的是首先找到第一个字母出现的位置,然后从该位置开始评估单词的其余部分。
到目前为止,我所做的只是有时有效。我能够在第一行垂直找到“猫”,但是当我尝试在对角线上找到比萨饼时,我得到了一个越界错误。我知道这意味着某些东西超出了数组,并且我知道如何在更简单的程序中修复它(例如遍历数组的 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);
}
}
}
}
如果有任何帮助,我将不胜感激。谢谢!
【问题讨论】:
-
当您“扫描”阵列时,您必须检查您是否到达阵列边界之外。这很简单。
colLocation + i离数组太远,所以会报错
标签: java arrays for-loop multidimensional-array