-2

当我编译测试器时,它在第 9 行说:

非静态方法 towersOfHanoi(int, int, int, int) 不能从静态上下文中引用

为什么它不能到达 towersOfHanoi 方法?

我提供了以下两个类。

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);
    }
}
4

2 回答 2

0

使 TowersOfHanoi.towersOfHanoi(int,int,int,int) 方法static

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

或更好,

实例化一个 TowersOfHanoi 对象,然后调用 towersOfHanoi 方法,而不是像你一样在类上调用它。

于 2014-03-10T04:42:51.133 回答
0

问题是这条线

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

要么创建一个对象TowersOfHanoi并在其上调用方法,要么将您的方法声明TowersOfHanoi.towersOfHanoi为静态。

于 2014-03-10T04:43:34.033 回答