完成に近づいているハノイの塔のパズル プログラムがあります。私の問題は、ユーザーからの入力を適切に機能させることです。
「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」と入力した場合に移動を表示するにはどうすればよいですか? また、ユーザーがこれ以外を入力した場合、出力には「Total Moves」だけが表示されますか?
これが私のコードです:
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 (
}
}