几乎在那里检查空int

时间:2013-11-06 07:28:25

标签: java recursion user-input

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

如何在最大光盘提示中检查空输入?如果用户没有输入任何内容,则默认为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);
        } 
    }
}

3 个答案:

答案 0 :(得分:1)

使用nextInt将没有空的整数

int height = minD.nextInt();

答案 1 :(得分:1)

行:

int heightmx = maxD.nextInt();

应该是:

String heightmx = maxD.nextLine();

答案 2 :(得分:1)

我希望

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

是一个拼写错误,因为你正在检查是否为空而不是相反(如你的评论所示)。

另外,使用

maxD.nextLine(); 

而不是

maxD.nextInt();