使用命令行参数完成hanoi程序?

时间:2013-11-06 07:05:21

标签: java recursion command-line command-prompt towers-of-hanoi

我刚刚完成了我的河内计划塔。它运行完美,除了现在我需要以某种方式使它,所以我的程序可以读取命令行参数(并产生与我的程序相同的结果)。我的程序执行与下面输出完全相同的任务,我只是不知道如何使它们看起来像下面的例子,因为我从未使用过命令行参数。

令我感到沮丧的是,无论如何,一些示例输入应该如下所示:

java hanoi 3 6将解决这个难题4次,分别为3个,4个,5个和6个磁盘 对于3个磁盘,java hanoi 3 2将解决一次难题 java hanoi dog 6将分别为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);
        } 
    }
}

4 个答案:

答案 0 :(得分:1)

你在

中有String [] args
public static void main(String[] args) {

数组中的第一个字符串是第一行参数,第二个字符串是第二行参数,... 检查大小,解析你需要的东西。

Greetz chill。

答案 1 :(得分:0)

public static void main(String[] args)

该魔术方法签名将包含您从命令行传递的任何String参数。

所以,例如:

java myProg a b c

运行程序时,a bc将成为args数组的一部分。这只是处理从命令行传入的args的问题。如果你通过它们,它们就会在那里。

答案 2 :(得分:0)

命令行参数传递给main()方法,因此它们在args中可用作字符串。只需检查有多少(args.length),如果给出了足够的参数,请将它们转换为与现在相同的数字。否则,请打印错误或使用isntructions并退出。

答案 3 :(得分:0)

命令行参数读取到String[] args,它作为参数传递给main方法。谷歌会发现这更快。

相关问题