문제

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);
    }
}
도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top