我今天制定了一个河内塔程序,对我来说的最后一步是在我的代码中实现输入的范围。
该程序将要求最小光盘数和最大光盘数。在此范围内,程序应解决此范围内每个增加的光盘数量的难题。
示例(根据我的代码):
输入最小光盘数:3输入最大光盘数:6
输出将分别求解 3、4、5 和 6 个光盘。
范围现在正在工作,除了,如果我有输入 say输入最小光盘数:3输入最大光盘数:2输出应仅解决最小数量的光盘,在这种情况下为 3 张光盘
法典:
import java.util.Scanner;
import java.util.*;
public class hanoi {
static int moves = 0;
static boolean displayMoves = false;
public static void main(String[] args) {
System.out.print(" Enter the minimum number of Discs: ");
Scanner minD = new Scanner(System.in);
String height = minD.nextLine();
System.out.println();
char source = 'S', auxiliary = 'D', destination = 'A'; // 'Needles'
System.out.print(" Enter the maximum number of Discs: ");
Scanner maxD = new Scanner(System.in);
int heightmx = maxD.nextInt();
System.out.println();
int iHeight = 3; // Default is 3
if (!height.trim().isEmpty()) { // If not empty
iHeight = Integer.parseInt(height); // Use that value
if (iHeight > heightmx){
hanoi(iHeight, source, destination, auxiliary);
}
System.out.print("Press 'v' or 'V' for a list of moves: ");
Scanner show = new Scanner(System.in);
String c = show.next();
displayMoves = c.equalsIgnoreCase("v");
}
for (int i = iHeight; i <= heightmx; i++) {
hanoi(i,source, destination, auxiliary);
System.out.println(" Total Moves : " + moves);
}
}
static void hanoi(int height,char source, char destination, char auxiliary) {
if (height >= 1) {
hanoi(height - 1, source, auxiliary, destination);
if (displayMoves) {
System.out.println(" Move disc from needle " + source + " to "
+ destination);
}
moves++;
hanoi(height - 1, auxiliary, destination, source);
}
}
}
main
方法倒数第二行的循环中调用 hanoi
方法。循环将从min
迭代到max
。
因此,您需要
...
for (int i = iHeight; i < heightmx; i++)
{
hanoi(i, ...);
}
然后,您的 for
循环变量 i
将从最小值变为最大值(也就是说,如果 min = 3 且 max = 6,则循环将使用 3、4、5 和 6 调用您的 hanoi
方法)。
--
一般建议:正确命名变量很重要。将来,当您处理一千个文件时,它可以为您节省一些挫败感。
char source = 'S', auxiliary = 'D', destination = 'A';
可能是
char source = 'S', auxiliary = 'A', destination = 'D';
如果您无论如何都将最大高度命名为heightMax
,那将是heightMin
height
.