The scanner does not stop at the entrance.

Well, a very noob question. I am creating a CLI application that allows users to create polls. First they ask a question, then they choose and choose. I use a scanner for input, and for some reason it allows the user to enter most things, but not the question text. The following is a snippet of code.

String title = "";
Question[] questions;
int noOfQuestions = 0;
int[] noOfChoices;
Scanner entry = new Scanner(System.in);
System.out.println("Please enter the title of the survey: ");
title = entry.nextLine();
System.out.println("Please enter the number of questions: ");
noOfQuestions = entry.nextInt();
noOfChoices = new int[noOfQuestions];
questions = new Question[noOfQuestions];
for (int i = 0; i < noOfQuestions; i++) {
    questions[i] = new Question();
}
for (int i = 0; i < noOfQuestions; i++) {

    System.out.println("Please enter the text of question " + (i + 1) + ": ");
    questions[i].questionContent = entry.nextLine();
    System.out.println("Please enter the number of choices for question " + (i + 1) + ": ");
    questions[i].choices = new String[entry.nextInt()];
    for (int j = 0; j < questions[i].choices.length; j++) {
        System.out.println("Please enter choice " + (j + 1) + " for question " + (i + 1) + ": ");
        questions[i].choices[j] = entry.nextLine(); 

    }
}

Thank:)

+3
source share
2 answers

The reason I asked if you are reading noOfQuestionsfrom the Scanner is because it Scanner.nextInt()does not use a separator (for example, a new line).

This means that the next call nextLine()you just get the empty string from the previous one readInt().

75\nQuestion 1: What is the square route of pie?
^ position before nextInt()

75\nQuestion 1: What is the square route of pie?
  ^ position after nextInt()

75\nQuestion 1: What is the square route of pie?
    ^ position after nextLine()

, , nextLine(), Integer.parseInt().

, ; BufferedReader.

+4

nextLine() , . , . sysout title = entry.nextLine() ,

, InputStreamReader BufferedReader.

0

Source: https://habr.com/ru/post/1766253/


All Articles