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");
}
}
My problem here is that when the loop started I can’t seem to input in the The question itself under the “Enter your Question” and same goes for others. any idea why?
What I am expecting is that the once I click enter it would go to “Enter The choices”.
But it seems they’re printing at the same time therefore rendering me to unable to answer the “Enter your question” should I fix this?
CollectionCreation is just returning an arrayList() using type inference
Beacuse you’re reading from
System.in, the Scanner won’t get any input until you hit enter. Thus when you read only an int usingnextInt(), there’s an extra newline in the buffer that isn’t read, and it gets instantly read in the nextinput.nextLine()call (which will be an empty String.Try changing the nextInt() to nextLine():
Alternatively, you can
reset()the scanner after thenextInt()call.