Hey guys, I have the assignment of writing the Towers of Hanoi program then testing it. I already got help measuring the time of the program, but that is not what my professor wanted he wanted to count the iterations. I can't get it down, my program will run but it will not print out correctly.

This is the code I was using.

import TerminalIO.KeyboardReader;

 public class towers
 {
  public static void main(String[] args)
  {
  
  
  KeyboardReader reader = new KeyboardReader();
  int numberofRings = reader.readInt("Enter number of Rings: ");
  move (numberofRings, 1, 3, 2);
  
  
  }
  
  static void move(int n, int i, int j, int k)
  {
  int count = 0;

  if (n > 0)
  {

  move(n - 1, i, k, j);

  System.out.println("Move ring " + n + "from peg" + i + "to" + j);
  
  

  move(n - 1, k, j, i);
  count++;
  
  }
  System.out.println(count+ "Is the number of Moves");
 }
}

And it keeps printing out
0 Is the number of Moves
Move ring 1 from peg 1 to 2
0 Is the number of Moves
1 Is the number of Moves
Move ring 2 from peg 1 to 3
0 Is the number of Moves

and repeating

Any help would be greatly appreaciated

move your

int count = 0;

to right before the move method. you are resetting the value each time you call that method, that's your problem.

I moved the line to a couple of other spots and I keep getting errors, I understand that I keep resetting my value, but I do not know where I am supposed to put it then. If I put it anywhere before

static void move(int n, int i, int j, int k)

It gives me an error for referencing a non static variable from a static position

replace:

static void move(int n, int i, int j, int k)
  {
  int count = 0;

by

static int count = 0;
static void move(int n, int i, int j, int k)
  {

if you declare a variable not as static, while it's on class scope, it'll be regarded as an instance variable. if you want to use an instance variable, you'll first have to instantiate the class and use the variable through this instance, but you don't need that in this case.

Thank you so much

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.