我今天制定了一个河内塔程序,对我来说最后一步是在我的代码中实现一个输入范围。
该程序将询问最小光盘数量和最大光盘数量。在这个范围内,程序应该解决这个范围内每个增加的光盘数量的难题。
示例(根据我的代码):
输入最小光盘数:3 输入最大光盘数:6
输出将分别求解 3、4、5 和 6 个圆盘。
范围现在正在工作,除非我输入说输入最小光盘数: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);
}
}
}