-2

When i compile the tester, it says that in line 9:

non-static method towersOfHanoi(int, int, int, int) cannot be referenced from a static context

Why cant it reach the towersOfHanoi method?

I provided the two classes below.

import java.io.*;
import java.util.*;
public class Tester
{
    public static void main(String args[])
    {
        Scanner swag = new Scanner(System.in);
        int yolo = swag.nextInt();
        TowersOfHanoi.towersOfHanoi(yolo,1,3,2);
    }
}
public class TowersOfHanoi
{
    public void towersOfHanoi (int N, int from, int to, int spare)
    {
        if(N== 1) 
        {
            moveOne(from, to);
        }
        else 
        {
            towersOfHanoi(N-1, from, spare, to);
            moveOne(from, to);
            towersOfHanoi(N-1, spare, to, from);
        }
    }  

    private void moveOne(int from, int to)
    {
        System.out.println(from + " ---> " + to);
    }
}
  • Which instance would it use? – alex Mar 10 '14 at 04:42
  • If it's static, it has no instance. So if you're attempting to access instance properties/methods, which instance would it use? Hint: it would have to guess, i.e. you can only call static from static – alex Mar 10 '14 at 04:44
  • possible duplicate of [What is the reason behind "non-static method cannot be referenced from a static context"?](http://stackoverflow.com/questions/290884/what-is-the-reason-behind-non-static-method-cannot-be-referenced-from-a-static) – Ron Mar 10 '14 at 04:45
  • thanks all your answers were helpful, and im sorry about the duplicate. – user3400297 Mar 10 '14 at 04:56

2 Answers2

0

make the TowersOfHanoi.towersOfHanoi(int,int,int,int) method static.

public static void towersOfHanoi (int N, int from, int to, int spare)
{

or better,

instantiate a TowersOfHanoi object then call the towersOfHanoi method instead of calling it on the class like you are.

Ron
  • 1,450
  • 15
  • 27
0

Problem is this line

TowersOfHanoi.towersOfHanoi(yolo,1,3,2);

either create an object of TowersOfHanoi and invoke method on that or declare your method TowersOfHanoi.towersOfHanoi as static.

Sanjeev
  • 9,876
  • 2
  • 22
  • 33