【问题标题】:Why does my java method act differently when made to run multiple times?为什么我的 java 方法在多次运行时表现不同?
【发布时间】:2020-12-28 16:32:46
【问题描述】:

当下面的这个方法checkUserInput()只被调用一次(当用户的第一个条目是从1到3的数字时)它工作正常。

但是,当多次调用该方法时,它会按预期打印出正确的错误消息并重新运行“Enter”。然而,当用户此时键入一个从 1 到 3 的数字时,程序的运行方式有所不同:它不将数字识别为数字,或者它不通过减一来转换数字,或者它到达末尾并且再次运行。

可能是什么原因?

static List checkUserInput() {
    System.out.print("Enter: ");
    int g = 0, h = 0;
    boolean numeric = true;
    boolean numera = true;
    Scanner scanner = new Scanner(System.in);
    int xAxis = 0, yAxis = 0, a = 0, r = 0;
    String m = scanner.next();

    try {
        yAxis = Integer.parseInt(m);
    } catch (NumberFormatException e) {
        numeric = false; //
    }

    if (!numeric) {
        System.out.println(" numbers only!"); //exclude letters
        checkUserInput();
    }

    String n = scanner.next();

    try {
        xAxis = Integer.parseInt(n);
    } catch (NumberFormatException e) {
        numera = false; //
    }

    if (!numera) {
        System.out.println(" numbers only!"); //exclude letters
        checkUserInput();
    } else if (xAxis < 1 || xAxis > 3 || yAxis < 1 || yAxis > 3) { 
        System.out.println("1 to 3 only!");
        checkUserInput();
    } else {
        //inputs that pass all tests can proceed
        //assign array indices to respective coordinates
        g = yAxis - 1;
        h = xAxis - 1;
    }

    cords = new ArrayList<Integer>();
    cords.add(g);
    cords.add(h);
    return cords;
}

【问题讨论】:

  • 我强烈建议你学习如何调试你的程序,它将帮助你理解它是如何工作的。

标签: java methods


【解决方案1】:

checkUserInput();

您似乎认为这会将执行重置为开始。不,它没有 - java 方法是可重入的。它将运行您的 checkUserInput 方法的另一个“副本”,一旦它返回,继续运行。因此,如果第一个 scanner.next() 调用返回一个非数字值,则“仅限数字!”错误处理块将再次运行整个方法,一旦整个方法完成,就会在String n = scanner.next() 继续运行,造成混乱。

这也意味着,如果您经常输入错误,您的代码将因 StackOverflowError 而爆炸。

我强烈建议您不要调用自己的方法。请改用 (do/)while 循环。

【讨论】:

  • 我尝试使用“do while”循环,但程序仍然没有按预期运行。它不遵守“do{}”中的条件语句,后续输出随第一个输入而变化。
  • 那么你就有了一个全新的、完全原创的新错误。编程很难,所有这些。我建议你问一个新的 SO 问题。确保粘贴所有代码。
猜你喜欢
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-28
  • 1970-01-01
  • 2021-08-03
  • 1970-01-01
相关资源
最近更新 更多