-2

很快就病倒了。我已经做了我能做的一切!问题:当我尝试在命令行中运行我的程序时,我收到了这个错误:

错误:找不到符号 SimpleDotCom dot = new SimpleDotCom(); ^ ^ 符号:SimpleDotCom 类 位置:SimpleDotComTestDrive 类

这是代码:

public class SimpleDotComTestDrive {

    public static void main (String[] args) {

        SimpleDotCom dot = new SimpleDotCom();

        int[] locations = {2, 3 ,4};

        dot.setLocationCells(locations);

        String userGuess = "2";

        String result = dot.checkYourself(userGuess);

    }

public class SimpleDotCom {

    int[] locationCells;
    int numOfHits = 0;

    public void setLocationCells(int[] locs) {
        locationCells = locs;   
    }

    public String checkYourself(String stringGuess) {

        int guess = Integer.parseInt(stringGuess);
        String result = "miss";
        for (int cell : locationCells) {

            if (guess == cell) {

                result = "hit";
                numOfHits++;
                break;

            }
        }   
        if (numOfHits == locationCells.length) {

            result = "kill";

        }

        System.out.println(result);
        return result;



   }

}
4

3 回答 3

1

该声明

SimpleDotCom dot = new SimpleDotCom(); 

失败,因为您无法在没有封闭实例的情况下实例化内部类。相反,你可以写

SimpleDotCom dot = (new SimpleDotComTestDrive()).new SimpleDotCom();

这将提供一个封闭的内联实例。或者,只需将类SimpleDotCom设为静态,这意味着它不会有封闭实例。

于 2013-10-25T12:41:41.717 回答
0

您需要将这两个类保存在不同的类文件中。此代码在 eclipse 和命令行编译器中都可以正常工作。

这是你必须做的。1) 创建一个名为 SimpleDotComTestDrive 的类并将这部分代码放入其中

public class SimpleDotComTestDrive {

    public static void main (String[] args) {

        SimpleDotCom dot = new SimpleDotCom();

        int[] locations = {2, 3 ,4};

        dot.setLocationCells(locations);

        String userGuess = "2";

        String result = dot.checkYourself(userGuess);

    }
}

然后创建另一个名为 SimpleDotCom 的类并粘贴此代码

public class SimpleDotCom {

    int[] locationCells;
    int numOfHits = 0;

void setLocationCells(int[] locs) {
        locationCells = locs;   
    }

    String checkYourself(String stringGuess) {

        int guess = Integer.parseInt(stringGuess);
        String result = "miss";
        for (int cell : locationCells) {

            if (guess == cell) {

                result = "hit";
                numOfHits++;
                break;

            }
        }   
        if (numOfHits == locationCells.length) {

            result = "kill";

        }

        System.out.println(result);
        return result;



   }

}
于 2014-09-04T15:37:08.887 回答
0

如果 SimpleDotCom 是内部类,则需要将其“分配”给外部类的实例

SimpleDotComTestDrive outer = new SimpleDotComTestDrive();
outer.SimpleDotCom dot = outer.new SimpleDotCom();

仍然这在静态环境中不起作用main

另一种选择是制作内部类static并通过 SimpleDotComTestDrive.SimpleDotCom

于 2013-10-25T12:43:21.147 回答