再次调用时如何在递归方法中打印另一条语句

问题描述 投票:0回答:2

addTeam
方法要求用户输入字符串。如果新团队不存在,则将其添加到数组列表中,否则再次运行该方法。

我想改变它,如果团队已经存在于列表中,它将打印“team already exists! Please enter a new name”并再次要求用户输入而不打印方法中的第一个打印语句。

编辑:我无法在方法之外创建新字段。此外,它不一定必须是递归方法。使用循环也可以使它工作?

public void addTeam(){
        System.out.print("Please enter the name of the team: ");
        String teamName = In.nextLine();   //In.nextLine() prompts user for String input
        if (teamExists(teamName) == null){ //teamExists() returns the team object if found else null 
            teams.add(new Team(teamName));
            System.out.println("Team " + teamName + " added! ");
        }
        else{
            System.out.print("Team " + teamName + " already exist! ");
            addTeam();
        }
        teamsPage();
    }

示例 I/O

Please enter the name of the team: Knicks
Team Knicks already exist! Please enter a new name: Lakers
Team Lakers already exist! Please enter a new name: Bulls
Team Bulls already exist! Please enter a new name: Warriors
Team Warriors added!
java recursion arraylist methods stdout
2个回答
1
投票

您必须维护某种

state
,它可以根据我们的目标
show first print statement
don't show first print statement
具有两个值,我们可以为此使用
boolean

所以在你的情况下,如果我们将

isAlreadyExist
保持为
boolean
我们可以开始使用
recursion
state management
来获得这种行为。

如下所示

public boolean isAlreadyExist = false;

public void addTeam(){
if(!isAlreadyExist) {
        System.out.print("Please enter the name of the team: ");
}
        String teamName = In.nextLine();
        if (teamExists(teamName) == null){ //teamExists() returns the team object if found else null 
            teams.add(new Team(teamName));
            System.out.println("Team " + teamName + " added! ");
            this.isAlreadyExist = false;
        }
        else{
            System.out.print("Team " + teamName + " already exist! ");
            this.isAlreadyExist = true;
            addTeam();
        }
        teamsPage();
    }

您也可以在函数参数中维护此状态,在这种情况下,您必须在调用函数时传递一个新状态,这会增加每次调用的堆栈内存,但如果您将状态维护为类变量本身或在其他语言中全局使用它可能会提高内存效率。


0
投票

方法不必是递归的。我按照评论的建议使用 while 循环实现了函数。

public void addTeam (){
        System.out.print("Please enter the name of the team: ");
        String teamName = In.nextLine();
        while (teamExists(teamName) != null){
            System.out.print("Team " + teamName + " already exist! Please enter a new name: ");
            teamName = In.nextLine();
        }
        teams.add(new Team(teamName));
        System.out.println("Team " + teamName + " added!");
        teamsPage();
    }

我喜欢 while 循环。

© www.soinside.com 2019 - 2024. All rights reserved.