[英]Strange behaviour when using recursion in an if statement, inside a method. Java
通過在線課程學習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
你能告訴我發生了什么嗎?
編輯:我讀了理解遞歸[關閉] ,但我還沒有找到有關遞歸如何影響調用堆棧的任何信息。 關於如何使用遞歸的信息很多,但是我仍然沒有找到我的問題的答案。
問題是您不希望在用戶進入課程的情況下打印遞歸,簡單的其他方法就可以解決問題
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.