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

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

java hanoi 3 6将分别为3、4、5和6个磁盘解决难题4次。
java hanoi 3 2将为3个磁盘解决一次难题。
java hanoi dog 6将分别为3、4、5和6个磁盘解决难题4次。

如何将程序转换为使用像这样的命令行参数?

码:

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);
        }
    }
}

最佳答案

您有String [] args

public static void main(String[] args) {


数组中的第一个字符串是您的第一行参数,第二个字符串是第二行参数,...
检查大小,解析为您需要的内容。

Greetz寒意。

07-24 09:37