我试图找出一个人如何乘以一个给定的名字在矩阵中重复,但我有一个无法修复的InputMismatchException。我认为问题出在scanner变量上,但我能理解问题出在哪里。
private static char[][] words= { { 'n', 'i', 'k', 'i' }, { 'e', 'v', 'n', 'h', }, { 'i', 'n', 'a', 'v', },
{ 'm', 'v', 'v', 'n', }, { 'q', 'r', 'i', 't', } };
private static void findName(int row, int col, String direction) {
Scanner input = new Scanner(System.in);
System.out.println("Enter name.");
String name = input.nextLine();
StringBuilder word = new StringBuilder();
int counter = 0;
if ((col < 0) || (row < 0) || (col >= words[0].length) || (row >= words.length)) {
// We are out of the labyrinth
return;
}
if (words[row][col] != ' ') {
// The current cell is not free
return;
} else {
word = word.append(lab[row][col]);
}
// Check if we have found the exit
if (word.equals(name)) {
counter++;
System.out.printf("Name - {%s} found %s times%n", name, counter);
word = null;
}
// Mark the current cell as visited
words[row][col] = 's';
// Invoke recursion the explore all possible directions
findName(row, col - 1, "L"); // left
System.out.printf("L");
findName(row - 1, col, "U"); // up
System.out.printf("U");
findName(row, col + 1, "R"); // right
System.out.printf("R");
findName(row + 1, col, "D"); // down
System.out.printf("D");
// Mark back the current cell as free
words[row][col] = ' ';
}
public static void main(String[] args) {
findName(0, 0, "R");
}发布于 2015-10-19 23:09:55
你说
System.out.println("Enter name.");
int name = input.nextInt();我假设您希望名称是一个String,而不是一个int。
因此您应该将其替换为
String name = input.nextLine();这也会修复您的InputMismatchError,当您稍后尝试将word与name进行比较时,可能会发生这种情况。尽管您可能必须在StringBuilder word上调用toString(),然后才能将其与String name进行比较。
https://stackoverflow.com/questions/33217821
复制相似问题