Reputation: 83
I have worked out a towers of hanoi program today, and the last step for me is to implement in my code a range for the inputs.
The program will ask for the minimum number of discs, and the maximum number of discs. With this range, the program should solve the puzzle for each incremented number of discs within this range.
Example (according to my code):
Enter the minimum number of Discs: 3 Enter the maximum number of Discs: 6
The output would solve for 3,4,5 and 6 discs, respectively.
RANGE IS WORKING NOW EXCEPT, if I have an input of say Enter the minimum number of Discs: 3 Enter the maximum number of Discs: 2 The output should only solve for the minimum number of discs, 3 discs in this case
Code:
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 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);
}
}
}
Upvotes: 0
Views: 252
Reputation: 794
You should be calling your hanoi
method in a loop on the second to last line of your main
method. The loop would iterate from min
to max
.
Thus, you would need
...
for (int i = iHeight; i < heightmx; i++)
{
hanoi(i, ...);
}
Your for
loop variable i
would then go from min to max (that is, if min = 3 and max = 6, the loop would call your hanoi
method with 3, then 4, then 5, then 6).
--
General advice: It's important to name your variables well. In the future, when you're dealing with a thousand files, it can save you some frustration.
char source = 'S', auxiliary = 'D', destination = 'A';
would probably be
char source = 'S', auxiliary = 'A', destination = 'D';
and height
would be heightMin
if you are anyway naming your max height heightMax
.
Upvotes: 1