从内部调用方法?

时间:2014-03-09 16:33:11

标签: java recursion methods

好的,所以我有一个显示菜单并返回用户选择的方法。

public class Menu {


public static int menuSelect(){

Scanner input = new Scanner(System.in);

System.out.println("Hello, Please Select A Function: ");
System.out.println("1) Sort All Banks Alphabetically ");
System.out.println("2) Calculate Interest And Show Balance ");
System.out.println("3) Transfer Money ");
System.out.println("4) Calulate Sum & Average Of All Accounts: ");
System.out.println("5) Richest Account: ");
System.out.println("6) Poorest Account: ");

int select = input.nextInt();

Menu.menuSelect();

 //i tried this as adding Menu.menuSelect(); 
 //after the return threw an error.
 // but surprise suprise this doesnt actually 
//let the method return anythign to select

  return select;
}

我的想法是,我希望菜单出现用户选择一个功能,功能发生,然后菜单调用自己,直到另有说明。 但我不确定如何做到这一点。 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

从自身调用相同的方法称为recursion,在您的情况下它是无限的。你显然在这里不需要它。

你想要这样的东西:

private static int getInput() {
    int choice = menuSelect();
    while(choice < 1 || choice > 6) {
        System.out.println("Invalid choice, please re-enter")
        choice = menuSelect();
    }
    return choice;
}

请注意,提供menuSelect public 修饰符是不好的,您不希望类外的任何人都可以访问它。