Towers.java (1192B)
1 package lab7; 2 3 import java.util.Scanner; 4 5 public class Towers { 6 Scanner in = new Scanner(System.in); 7 public static int count = 0; 8 public static int moves = 0; 9 10 public static void main(String args[]) { 11 int n; 12 13 Towers towers = new Towers(); 14 15 n = towers.getInput(); 16 towers.solve(n, "Initial", "Destination", "Temporary"); 17 count++; 18 System.out.println("Number of method calls: " + count); 19 System.out.println("Number of disk moves " + moves); 20 21 } 22 23 public void solve(int n, String Initial, String Destination, String Temp) { 24 count++; 25 if (n == 1) { 26 System.out.println("Move disk 1 from: " + Initial + " to " + Destination); 27 moves++; 28 } 29 else { 30 solve(n - 1, Initial, Temp, Destination); 31 System.out.println("Move disk " + n + " from " + Initial + " to " + Destination); 32 moves++; 33 solve(n - 1, Temp, Destination, Initial); 34 } 35 } 36 37 public int getInput() { 38 int userIn; 39 System.out.print("Enter number of towers: "); 40 userIn = Integer.parseInt(in.nextLine()); 41 return userIn; 42 } 43 }