views:

12

answers:

2

Alright, very noob question. I'm making a CLI app that lets users design surveys. First they enter the question, then the number of choices and the choices. I'm using a Scanner to get input, and for some reason it lets the user enter most things, but not the text of the question. Code snippet below.

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

    }
}

Thanks :)

A: 

The documentation for nextLine() says Advances this scanner past the current line and returns the input that was skipped. Might explain the behavior you are seeing. Just to verify you can add a sysout and print the value of title after the title = entry.nextLine() and see what value it is holding

If you want to read a complete line from the input you might want to use the InputStreamReader combination with BufferedReader.

Sagar V
Yeah, but I used nextLine several times, and it's only skipped at the "question text" part. It didn't skip at the "enter title" part, for instance.
Anita
+1  A: 

The reason I asked about whether you read noOfQuestions from the Scanner is because Scanner.nextInt() does not consume the delimiter (e.g. the new line).

That means that the next time you call nextLine(), you will just get an empty String from the previous 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()

My suggestion is to just read by line, always with nextLine(), and then parse afterwards using Integer.parseInt().

If that's the route you take, there's little need for a Scanner at all; you can just accept a BufferedReader.

Mark Peters
Awesome! Works now! :)
Anita
The alternative is to pair each nextInt() with a nextLine() whose result you discard, but that gets messy.
Mark Peters