1

在我的河内塔程序中,我试图检查用户在提示输入“最小光盘”和“最大光盘”时是否没有输入任何输入。我最初只有最少的光盘并且可以正常工作,现在当提示输入“最大光盘”时,我似乎无法通过检查空输入

如何在我的最大光盘提示中检查空输入?如果用户没有输入任何内容,则默认为解决我的 3 张光盘难题。

我在代码中注释掉了我试图解决的问题

代码:

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();
      System.out.println();

//       int iMax = 3;
//       if (heightmx.isEmpty()) {   //If not empty
//          iMax = Integer.parseInt(heightmx);
//          hanoi(iMax, source, destination, auxiliary);
//       }  


      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

3 回答 3

1

使用nextInt不会有空整数

int height = minD.nextInt();
于 2013-11-06T07:30:52.030 回答
1

线:

int heightmx = maxD.nextInt();

应该:

String heightmx = maxD.nextLine();
于 2013-11-06T07:32:11.553 回答
1

我希望

if (heightmx.isEmpty()) {   //If not empty

是一个错字,因为您正在检查空而不是相反(就像您的评论所暗示的那样)。

另外,使用

maxD.nextLine(); 

代替

maxD.nextInt();
于 2013-11-06T07:34:09.783 回答