如果/ else语句为某些情况

时间:2013-11-06 04:35:59

标签: 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         
//       }   
    }
}

1 个答案:

答案 0 :(得分:1)

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

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.

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

编辑:如果不需要显示步骤的选项,则需要添加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");
}