我正在尝试显示解决汉诺塔谜题的程序中的移动计数,但它不断显示计数,如下面的输出所示
Input the number of rings: 2
Towers of Hanoi with 2 rings
1
3
3
我希望它只显示数字 3 一次,而不是 1、3、3。下面是我的代码(对于我的作业,我必须声明一个静态 int 计数)。
import java.util.Scanner;
public class Towers
{
static int count;
public static void doTowers(
int n, // Number of rings to move
int startPeg, // Peg containing rings to move
int auxPeg, // Peg holding rings temporarily
int endPeg ) // Peg receiving rings being moved
{
boolean b = true;
while(b){
if (n == 1){ // Base case - Move one ring
count = count + 1;
b = true;
}
if (n == 0){
b = false;
}
else{
// Move n - 1 rings from starting peg to auxiliary peg
doTowers(n - 1, startPeg, endPeg, auxPeg);
count = count + 1;
b = true;
// Move n - 1 rings from auxiliary peg to ending peg
doTowers(n - 1, auxPeg, startPeg, endPeg);
}
}
}
public static void main(String[] args)
{
Scanner conIn = new Scanner(System.in);
// Number of rings on starting peg.
int n;
System.out.print("Input the number of rings: ");
if (conIn.hasNextInt())
n = conIn.nextInt();
else
{
System.out.println("Error: you must enter an integer.");
System.out.println("Terminating program.");
return;
}
if (n < 1)
{
System.out.println("Error: you must enter an integer >= 1.");
System.out.println("Terminating program.");
return;
}
System.out.println("Towers of Hanoi with " + n + " rings ");
doTowers(n, 1, 2, 3);
System.out.println("This takes " + count + " moves.");
} }
最佳答案
您可以在 main
中打印计数,而不是在 doTowers
方法中使用 System.out.println(count);
被执行,例如:
doTowers(n, 1, 2, 3);
System.out.println(count);
这不会多次打印 count
(在您的情况下发生这种情况的原因是因为 doTowers
进行了递归调用并具有 sysout
语句,因此每次调用都会生成一个 sysout
)。
关于java - 在java中使用static int打印计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42461131/