-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

SimpleDotCom が内部クラスの場合、外部クラスのインスタンスに「割り当てる」必要があります

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

それでも、これは静的環境ではそのままでは機能しませんmain

他のオプションは、内部クラスstaticを作成し、それを介してアクセスすることです SimpleDotComTestDrive.SimpleDotCom

于 2013-10-25T12:43:21.147 に答える
0

これら 2 つのクラスは、異なるクラス ファイルに保持する必要があります。このコードは、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 に答える