gpt4 book ai didi

java - 如果语句在汉诺塔解决方案中无法正常工作

转载 作者:行者123 更新时间:2023-12-02 04:54:08 24 4
gpt4 key购买 nike

在这段代码中,为了找到汉诺塔问题的解决方案,我将 N(磁盘数量)设置为 4,作为示例,当我运行时,它会打印出以下内容:

import java.util.Scanner;
public class HanoiTower {

public static void main(String[] args) {
int N;
Scanner in=new Scanner(System.in);
System.out.println("Choose number of disks? ");
N= in.nextInt();
in.close();
towers(N,0,1,2);
}

static void towers(int disks, int a,int b, int spare){

if (disks==1){
System.out.println("Move disk 1 from 1 to 2 ");
}
else{
towers(disks-1, a,spare,b);
System.out.printf("Move disk %d from stack %d to stack %d ", disks, a, b);
towers(disks-1,spare,b,a);
}
}
}

我的疑问是为什么它首先打印 if 语句?

 Move disk 1 from 1 to 2 
Move disk 2 from stack 0 to stack 2 Move disk 1 from 1 to 2
Move disk 3 from stack 0 to stack 1 Move disk 1 from 1 to 2
Move disk 2 from stack 2 to stack 1 Move disk 1 from 1 to 2
Move disk 4 from stack 0 to stack 2 Move disk 1 from 1 to 2
Move disk 2 from stack 1 to stack 0 Move disk 1 from 1 to 2
Move disk 3 from stack 1 to stack 2 Move disk 1 from 1 to 2
Move disk 2 from stack 0 to stack 2 Move disk 1 from 1 to 2
Move disk 5 from stack 0 to stack 1 Move disk 1 from 1 to 2
Move disk 2 from stack 2 to stack 1 Move disk 1 from 1 to 2
Move disk 3 from stack 2 to stack 0 Move disk 1 from 1 to 2
Move disk 2 from stack 1 to stack 0 Move disk 1 from 1 to 2
Move disk 4 from stack 2 to stack 1 Move disk 1 from 1 to 2
Move disk 2 from stack 0 to stack 2 Move disk 1 from 1 to 2
Move disk 3 from stack 0 to stack 1 Move disk 1 from 1 to 2
Move disk 2 from stack 2 to stack 1 Move disk 1 from 1 to 2

最佳答案

您的方法towers会递归,直到disks等于1。您可以在开头记录disks的值,例如

static void towers(int disks, int a, int b, int spare) {
System.out.printf("Disks = %d%n", disks);
if (disks == 1) {
System.out.println("Move disk 1 from 1 to 2 ");
} else {
towers(disks - 1, a, spare, b);
System.out.printf("Move disk %d from stack %d to stack %d ", disks,
a, b);
towers(disks - 1, spare, b, a);
}
}

您可以看到为什么会得到这样的输出。另外,关闭 System.in 周围的 Scanner 也是一个坏主意(一旦关闭 System.in,就无法再次打开它)。

关于java - 如果语句在汉诺塔解决方案中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28944518/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com