在方法内部的if语句中使用递归时的奇怪行为。爪哇

时间:2018-08-25 17:29:17

标签: java recursion methods

在通过在线课程学习Java的同时,我正在尝试使用本教程编写的一些代码。有一种方法可以连接“课程”,最后将它们打印出来。我想使用递归而不是循环。

private String courses = "";
private int tuitionBalance = 0;

public void enroll() {
    System.out.println("Enter course to enroll or \"Q\" to quit.");
    Scanner in = new Scanner(System.in);
    String course = in.nextLine();
    if (!course.equalsIgnoreCase("q")) {
        courses = courses + "\n" + course;
        tuitionBalance = tuitionBalance + costOfCourse;
        enroll();
    }

    System.out.println("Enrolled in: " + courses);
    System.out.println("Tuition balance: " + tuitionBalance);
    return; // even with "return", this method executes multiple times after leaving if statement.
}

此方法运行时,它会一直提示输入,直到按下'Q'。串联工作正常。然后,它留下“ if语句”,并且(对于我来说很奇怪)它运行了最后两行println代码,次数与提供的输入相同。

例如,当我输入三种类型的“课程”然后按“ Q”时,输出为:

Enter course to enroll or "Q" to quit.
History  // My entry
Enter course to enroll or "Q" to quit.
Math  // My entry
Enter course to enroll or "Q" to quit.
Biology  // My entry
Enter course to enroll or "Q" to quit.
q  // My entry
Enrolled in: 
History
Math
Biology
Tuition balance: 1800
Enrolled in: 
History
Math
Biology
Tuition balance: 1800
Enrolled in: 
History
Math
Biology
Tuition balance: 1800
Enrolled in: 
History
Math
Biology
Tuition balance: 1800

Process finished with exit code 0

你能告诉我发生了什么吗?

编辑:我已经读过Understanding recursion [closed],但没有发现有关递归如何影响调用堆栈的任何信息。关于如何使用递归的信息很多,但是我仍然没有找到我的问题的答案。

1 个答案:

答案 0 :(得分:0)

问题是您不想在用户进入课程的情况下打印递归,简单的其他方法就可以解决问题

private String courses = "";
private int tuitionBalance = 0;

public void enroll() {
    System.out.println("Enter course to enroll or \"Q\" to quit.");
    Scanner in = new Scanner(System.in);
    String course = in.nextLine();
    if (!course.equalsIgnoreCase("q")) {
        courses = courses + "\n" + course;
        tuitionBalance = tuitionBalance + costOfCourse;
        enroll(); 
    }
    else{//now it would come here only once after user has entered q after which it returns
    System.out.println("Enrolled in: " + courses);
    System.out.println("Tuition balance: " + tuitionBalance);
     }
    return;
}