在我的河内塔程序中,我正在尝试检查用户在提示输入"最小光盘"和"最大光盘"时是否没有输入任何输入。我最初只有最少的光盘并让它工作,现在当提示输入"最大光盘数"时,我似乎无法通过检查空输入
如何在最大光盘数提示符上检查空输入?如果用户没有输入任何内容,则默认为解决我的 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);
}
}
}
使用nextInt
将没有空整数
int height = minD.nextInt();
我希望
if (heightmx.isEmpty()) { //If not empty
是一个错字,因为您正在检查空而不是相反(就像您的评论所建议的那样)。
另外,使用
maxD.nextLine();
而不是
maxD.nextInt();
行:
int heightmx = maxD.nextInt();
应该是:
String heightmx = maxD.nextLine();