我有一个河内拼图程序塔正在接近完成。我现在的问题是试图让用户输入正常工作。
如果他们输入'v'或'V',则会显示解决拼图的步骤(因此输出将是'将光盘从S移动到D'等等)。否则,如果用户没有输入'v'或'V',则程序继续解决拼图,显示总动作但不显示步骤。
我遇到的问题是选项不像他们应该的那样工作。
现在唯一不对的是当用户输入'v'或'V'时,移动没有正确显示。 输出:
Enter the min number of discs :
2
Press 'v' or 'V' for a list of moves
v
Move disc from needle S to A
Total Moves : 3
如果用户键入“v”或“V”,如何显示移动,如果用户键入除此之外的其他输出,则输出只显示“总移动”? < / p>
这是我的代码:
import java.util.*;
import java.util.Scanner;
public class TowerOfHanoi4 {
static int moves=0;
public static void main(String[] args) {
System.out.println("Enter the min number of discs : ");
Scanner scanner = new Scanner(System.in);
int iHtMn = scanner.nextInt(); //iHeightMin
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();
// char lstep='v', lsteps='V'; // grab option v or V
if (c.equalsIgnoreCase("v")){ //if option is not v or V, execute code and only display total moves
hanoi(iHtMn, source, destination, auxiliary); //else, user typed v or V and moves are displayed
System.out.println(" Move disc from needle "+source+" to "+destination);
System.out.println(" Total Moves : "+moves);
} else {
hanoi(iHtMn, source, destination, auxiliary);
System.out.println(" Total Moves : "+moves);
}
}
static void hanoi(int htmn,char source,char destination,char auxiliary)
{
if (htmn >=1)
{
hanoi(htmn-1, source, auxiliary, destination); // move n-1 disks from source to auxilary
// System.out.println(" Move disc from needle "+source+" to "+destination); // move nth disk to destination
moves++;
hanoi(htmn-1, auxiliary, destination, source);//move n-1 disks from auxiliary to Destination
}
// else (
}
}
答案 0 :(得分:3)
检查此行
if (c != lstep || c != lsteps){////}
即使c是v或V,这也会起作用 如果c ='v'则c!='V',所以这个'if test'适用于v或V. 将其更改为
if (c != lstep && c != lsteps){
答案 1 :(得分:1)
您的代码的问题是else if
条件,当您键入v
或V
时,应用程序会转到第一个if和条件为true,因此您的{{ 1}}永远不会被执行。
一个else if
条件就足够了,试试这个
if
顺便说一句,您的代码中不需要多个扫描程序,只有一个就足够了。
也无需定义两个//if option is not v or V, execute code and only display total moves
//else, user typed v or V and moves are displayed
if (c == lstep || c == lsteps){
hanoi(iHeight, source, destination, auxiliary);
System.out.println(" Move disc from needle "+source+" to "+destination);
System.out.println(" Total Moves : "+moves);
} else {
hanoi(iHeight, source, destination, auxiliary);
System.out.println(" Total Moves : "+moves);
}
来与它们进行比较,您可以轻松地执行此操作:
char
更新根据您的上次修改,您可以定义静态String c = show.next();
//if option is not v or V, execute code and only display total moves
//else, user typed v or V and moves are displayed
if (c.equalsIgnoreCase("v")){
hanoi(iHeight, source, destination, auxiliary);
System.out.println(" Move disc from needle "+source+" to "+destination);
System.out.println(" Total Moves : "+moves);
} else {
hanoi(iHeight, source, destination, auxiliary);
System.out.println(" Total Moves : "+moves);
}
字段并将if条件移至boolean
方法
检查pastebin here