Java从用户那里获得用户输入

时间:2012-08-16 00:58:38

标签: java printing input java.util.scanner system.out

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()

1 个答案:

答案 0 :(得分:2)

由于你正在从System.in阅读,扫描仪在你输入之前不会得到任何输入。因此,当您使用nextInt()只读取一个int时,缓冲区中有一个额外的换行符未被读取,并且会在下一个input.nextLine()调用中立即读取(这将是一个空字符串。< / p>

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

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

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