我今天制定了一个汉诺塔程序,最后一步是在我的代码中实现输入范围。
程序将询问最小光盘数和最大光盘数。有了这个范围,程序应该解决这个范围内每个增加的圆盘数量的难题。
示例(根据我的代码):
输入最小光盘数量: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);
}
}
}
最佳答案
您应该在 main
方法的倒数第二行循环中调用 hanoi
方法。循环将从 min
迭代到 max
。
因此,您需要
...
for (int i = iHeight; i < heightmx; i++)
{
hanoi(i, ...);
}
您的 for
循环变量 i
将从 min 到 max(也就是说,如果 min = 3 且 max = 6,则循环将调用您的 hanoi
方法,先是 3,然后是 4,然后是 5,然后是 6)。
--
一般建议:正确命名变量非常重要。将来,当您处理一千个文件时,它可以为您省去一些挫败感。
char source = 'S', auxiliary = 'D', destination = 'A';
可能是
char source = 'S', auxiliary = 'A', destination = 'D';
如果您无论如何都将最大高度命名为 heightMax
,和 height
将为 heightMin
。
关于Java范围输入困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19804870/