无法弄清楚如何将此递归方法更改为迭代方法,任何人都有任何有用的指针?我得到了递归方法的工作原理,但不太确定转换为迭代的步骤,谢谢。
private static void printFriends(Friend friend, int distance) {
if (distance == 0) {
System.out.println(friend);
} else {
for (Friend f : friend.getFriends()) {
System.out.println(f + "0");
printFriends(f, distance - 1);
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
List<Friend> friendList = new ArrayList<Friend>();
Friend reuben = new Friend("Reuben");
Friend soumitra = new Friend("Soumitra");
Friend ken = new Friend("Ken");
Friend elisa = new Friend("Elisa");
Friend isaac = new Friend("Isaac");
friendList.add(reuben);
friendList.add(soumitra);
friendList.add(ken);
friendList.add(elisa);
friendList.add(isaac);
reuben.addFriend(soumitra);
reuben.addFriend(ken);
soumitra.addFriend(reuben);
ken.addFriend(reuben);
ken.addFriend(elisa);
elisa.addFriend(ken);
elisa.addFriend(isaac);
isaac.addFriend(elisa);
BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in));
String inputName = "";
String inputValue = "";
Friend inputFriend = null;
int inputInt = 0;
System.out.println("Blank entry at any prompt exits program.");
while (true) {
System.out.print("Enter a person's name: ");
try {
inputName = inputReader.readLine();
} catch (IOException e) {
System.err.println("Error reading from console.");
}
if (inputName.equals("")) {
System.out.println("Run complete.");
System.exit(0);
}
inputFriend = new Friend(inputName);
if (friendList.contains(inputFriend)) {
inputFriend = friendList.get(friendList.indexOf(inputFriend));
System.out.print("Enter a non-negative integer: ");
try {
inputValue = inputReader.readLine();
} catch (IOException e) {
System.err.println("Error reading from console.");
}
if (inputValue.equals("")) {
System.out.println("Run complete.");
System.exit(0);
}
try {
inputInt = Integer.valueOf(inputValue);
} catch (NumberFormatException e) {
System.err.println("Must enter integer.");
continue;
}
if (inputInt < 0) {
System.out.println("Must be non-negative");
} else {
printFriends(inputFriend, inputInt);
}
} else {
System.out.println(inputFriend + " not found.");
}
}
}
}
答案 0 :(得分:1)
查看您的代码,您似乎正在使用距离&#39;参数作为要打印的朋友数的计数器,因此是递归调用该方法的次数。您可以使用for循环或while循环结构轻松转换它,并使用distance参数作为循环的终止条件。我建议使用for循环,因为它有助于简化代码。
For loop construct:https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
for (int i = 0; i < distance; i++) {
//list.get(i);
//printfriends + "0"
}
确保熟悉java中的所有基本循环结构。