java - 针对特定情况的 if/else 语句

标签 java recursion user-input towers-of-hanoi

嗨,这是一个汉诺塔益智程序。现在,如果提示“输入光盘数量”为空(即按下回车键而不输入任何整数值),我无法让程序求解 3 张光盘。

*我认为问题出在我的 hanoi 方法中的 if/else 语句。我评论了我认为问题出在哪里。如果在提示“输入光盘数量”时未输入任何内容,如何让程序仅求解 3 个光盘?*

代码:

import java.util.Scanner;

public class TowerOfHanoi4 {
    static int moves = 0;
    static boolean displayMoves = false;
   static int blank = 3;

    public static void main(String[] args) {

        System.out.println("Enter the Number of Discs : ");
        Scanner scanner = new Scanner(System.in);
        int iHeight = scanner.nextInt();
        char source = 'S', auxiliary = 'D', destination = 'A'; // name poles or
                                                                // 'Needles'

        System.out.println("Press 'v' or 'V' for a list of moves");
        Scanner show = new Scanner(System.in);
        String c = show.next();
        displayMoves = c.equalsIgnoreCase("v");


        hanoi(iHeight, 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);
        }
//       else (height == blank) {                                  //I think the problem
//          hanoi(height - 1, source, auxiliary, destination);//Lies with this
//          moves++;                                          //else
//          hanoi(height - 1, auxiliary, destination, source);//statement         
//       }   
    }
}

最佳答案

您可以在获取输入本身后立即进行检查,而不是在方法中检查它。

String height = scanner.nextLine();
int iHeight = height.trim().isEmpty() ? 3 : Integer.parseInt(height);
// The above code snippet will read the input and set the iHeight value as 3 if no input is entered.

并从 hanoi() 方法中删除 else 部分。

编辑:如果不需要显示步骤的选项,则需要添加 if 并在其中显示显示步骤的选项。

String height = scanner.nextLine();
int iHeight = 3; // Default is 3
if (!height.trim().isEmpty()) { // If not empty
    iHeight = Integer.parseInt(height); // Use that value

    // And display the option to show steps
    System.out.println("Press 'v' or 'V' for a list of moves");
    Scanner show = new Scanner(System.in);
    String c = show.next();
    displayMoves = c.equalsIgnoreCase("v");
}

关于java - 针对特定情况的 if/else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19804206/

相关文章:

javascript - JSON 数据转换为看起来像表格的 HTML 列表

Javascript 表单输入值与输入最大值的比较

java - 如何让 JTable 上的 MouseListener 正常工作

c++ - 递归加法序列C++

c++ - 函数递归的最大次数c++

python - 如何检查给定文件是否为 FASTA?

java - 在java中将递归帕斯卡三角形居中?

java - 在Java中使用正则表达式在字符串中添加分隔符

java - 是否强制/推荐使用 requireExplicitBindings

eclipse - 取决于 Eclipse 中 tools.jar (Sun JDK) 的 com.sun.javadoc