0
import java.util.List;

import ShortHand.utilities.CollectionCreation;

public class MultipleChoice<Q,A,C>
{
    Q question;
    A answer;
    C choices;

    public MultipleChoice(Q q, A a, C c){
        question = q;
        answer = a;
        choices = c;
    }

    public Q getQuestion(){ return question;  }
    public A getAnswer(){ return answer;  }
    public C getChoices(){ return choices;  }

    public void addChoices(C c ){ choices = c; }
    public void addQuestion(Q q){ question = q; }
    public void addAnswer(A a){ answer = a; }

    public String toString(){
         return "Question: "+this.getQuestion()+ "\n"+
                "Choices: "+this.getChoices();
    }

    public static void main(String[] args){
        java.util.Scanner input = new java.util.Scanner(System.in);

        List<MultipleChoice<String,String,String>> mc = CollectionCreation.list();
        int numOfQuestions;
        System.out.print("Enter number of Question: ");
        numOfQuestions = input.nextInt();
        System.out.println();
        for(int i = 0; i< numOfQuestions; i++){
            System.out.println("Enter Question: ");
            String question = input.nextLine();
            System.out.println("Enter choices: ");
            String choices = input.nextLine();
            System.out.println("Enter Answer: ");
            String answer = input.nextLine();
            mc.add(new MultipleChoice(question,choices,answer));
        }

        for(MultipleChoice<String, String, String> items : mc)
            System.out.println(items+"\n");

    }
}

我的问题是,当循环开始时,我似乎无法在“输入您的问题”下的问题本身中输入,其他人也是如此。知道为什么吗?

我所期待的是,一旦我单击输入,它将转到“输入选择”。

但似乎他们正在同时打印,因此让我无法回答“输入您的问题”我应该解决这个问题吗?

CollectionCreation 只是使用类型推断返回一个 arrayList()

4

1 回答 1

2

因为您正在阅读System.in,所以在您按 Enter 之前,扫描仪不会获得任何输入。因此,当您使用 仅读取一个 int 时nextInt(),缓冲区中会有一个额外的换行符未被读取,并且它会在下一次input.nextLine()调用中立即读取(这将是一个空的 String.

尝试将 nextInt() 更改为 nextLine():

numOfQuestions = Integer.parseInt(input.nextLine().trim());

或者,您可以reset()nextInt()通话后扫描仪。

于 2012-08-16T01:12:13.877 回答