首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >回溯算法中的InputMismatchException

回溯算法中的InputMismatchException
EN

Stack Overflow用户
提问于 2015-10-19 23:04:39
回答 1查看 43关注 0票数 1

我试图找出一个人如何乘以一个给定的名字在矩阵中重复,但我有一个无法修复的InputMismatchException。我认为问题出在scanner变量上,但我能理解问题出在哪里。

代码语言:javascript
复制
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");
}
EN

回答 1

Stack Overflow用户

发布于 2015-10-19 23:09:55

你说

代码语言:javascript
复制
System.out.println("Enter name.");

int name = input.nextInt();

我假设您希望名称是一个String,而不是一个int

因此您应该将其替换为

代码语言:javascript
复制
String name = input.nextLine();

这也会修复您的InputMismatchError,当您稍后尝试将wordname进行比较时,可能会发生这种情况。尽管您可能必须在StringBuilder word上调用toString(),然后才能将其与String name进行比较。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33217821

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档