views:

53

answers:

2

I'm making an app that lets people make surveys. My idea is to let people enter unlimited choices for a question, and to signal when they're done with that question by pressing Enter on a new line, at which point I let them enter the next question and that question's choices. I thought that pressing Enter on an empty line would result in a null, and wrote the while loop condition to break on null, but as the code is, below, it doesn't break on null, but carries right on asking users for more choices. Then I thought maybe an empty line is actually "" instead of null. But when I do that...NullPointerException. I hope I'm making sense here.

Essentially, the question is, how do I make the inner loop break and proceed to the next iteration of the outer loop?

Thanks!

public class Survey implements Serializable {
    String title = "";
    ArrayList<Question> questions;
    String surveyFileName;
//survey entry code
//entry is a Scanner defined in the Main class
while ((currentQn.questionContent = (Main.entry.nextLine())).equals("") == false) {
            currentQn.choices.clear();
            System.out.println("Please enter the text of question " + currentQnNo + ": ");
            String currentChoice = "";
            int currentChoiceNo = 1;
            System.out.println("Please enter choice " + currentChoiceNo + " for question " + currentQnNo + ": ");
            while ((currentChoice = (Main.entry.nextLine())) != null) {
                System.out.println("Please enter choice " + currentChoiceNo + " for question " + currentQnNo + ": ");
                currentQn.choices.add(currentChoice);
                currentChoiceNo++;
            }
            currentQnNo++;
            questions.add(currentQn);
        }

and here's Question's implementation:

package surveyor;

import java.io.Serializable;
import java.util.*;

class Question implements Serializable {
    public String questionContent = ""; //initialize these so no NPEs
    public ArrayList<String> choices = new ArrayList<String>();

}
A: 

before inner while loop

 bool shouldContinue = false;

in inner while loop

if ("".equals(currentChoice.trim())) {
    shouldContinue = true;
    break;
}

after inner while loop

if (shouldContinue) continue;
hvgotcodes
A: 

Whoops, never mind. The NPE was not for the empty string. It was for the ArrayList<Question> questions, which wasn't initialized. Scanner indeed gets an empty string, not null.

Anita