0

私は現在、テストを含むプログラムを書いています。ユーザーが送信をクリックすると、正しいか間違っているかのいずれかが出力され、別のクラスに移動します。これを行うだけでなく、変数に1を追加する答えが正しいかどうかを知りたいです。

私がうまくいかないのは、異なるクラスで同じプロジェクトに保存されているすべての質問に1または0を追加する必要があるため、異なるクラスでこれを行う方法です。

4

4 に答える 4

1

各質問が個別のクラスである理由はありますか? 次のようなインスタンス変数を保持する単一の Question クラスを持つことができるようです

public class Question{
    private String text; //the question itself
    private String[] choices; //the choices if this is a multiple-choice question
    private int answer; //the index in choices that is the correct answer

    //constructor, accessors, mutators

    public String toString(){
        String retval = this.text+"\n";
        for(int x=0;x<choices.length;x++){
            char c = 'a'+x; //this will give characters going alphabetically from 'a'
            retval+=c+") "+choices[x]+"\n";
        }
        return retval;
    }
}

次に、メイン メソッドを持つ Test クラスを作成できます。

public class Test{

    public static void main(String args[]){
        Question[] questions = {
            new Question("What is 1+1?", new String[]{"2", "3", "4"}, 0),
            //other questions here
        }

        int total=0;
        Scanner input = new Scanner(System.in);

        for(Question q: questions){
            System.out.println(q.toString());
            int ans = input.nextLine().charAt(0)-'a';
            if(q.getAnswer()==ans){
                total++;
            }
        }
    }
}

これはあなたが望むことをしますか?

于 2011-03-16T15:24:47.910 に答える
0

質問への参照を持っているクラスが何であれ、それらをループして、正しい質問の合計を合計する必要があります。質問が同じクラスから継承されていない場合は、呼び出すことができる isAnswerRight() メソッドを持つ Question という名前のインターフェイス、または同様のものを作成します。

于 2011-03-16T15:10:58.120 に答える
0

public final static クラスと変数を持つ別のクラスが必要です。

このようなもの:

public class Counter {
    private static int count=0;
    public static int add() {
        return count++;
    }
}

ゲッターも必要になる場合があります。

于 2011-03-16T15:10:44.173 に答える
0

このカウンターには、個々のクラスのそれぞれにコンテキストがありません。実行中のこれらのテストを管理しているコード内にのみコンテキストがあります。したがって、このマネージャー クラス内には、テストが完了し、それが正しいことを検出するたびにインクリメントする変数が 1 つあります。

于 2011-03-16T15:09:38.127 に答える