我刚刚完成了我的河内塔计划。它完美无瑕,除了现在我需要以某种方式使它可以读取命令行参数(并产生与我的程序相同的结果)。我的程序执行与下面的输出完全相同的任务,我只是不知道如何使它们看起来像下面的示例,因为我从未使用过命令行参数。
无论如何,对我来说令人沮丧的是,一些示例输入应该如下所示:
java hanoi 3 6
将解谜 4 次,分别为 3、4、5 和 6 个磁盘。
java hanoi 3 2
将解决难题一次,为 3 个磁盘。
java hanoi dog 6
将解谜 4 次,分别为 3、4、5 和 6 个磁盘。
如何将我的程序转换为使用这样的命令行参数?
代码:
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();
// if (heightmx.isEmpty()) { //If not empty
// // iMax = Integer.parseInt(heightmx);
// int iMax = 3;
// hanoi(iMax, source, destination, auxiliary);
// }
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);
}
}
}