【发布时间】:2010-09-30 02:55:29
【问题描述】:
我正在制作一个可以让人们进行调查的应用。我的想法是让人们为一个问题输入无限的选择,并在他们完成该问题时通过在新行上按 Enter 来发出信号,此时我让他们输入下一个问题和该问题的选择。我认为在空行上按 Enter 会导致 null,并编写了 while 循环条件以在 null 上中断,但正如下面的代码所示,它不会在 null 上中断,而是继续向用户询问更多信息选择。然后我想也许一个空行实际上是“”而不是null。但是当我这样做时...... NullPointerException。我希望我在这里说得通。
本质上,问题是,如何使内循环中断并继续进行外循环的下一次迭代?
谢谢!
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);
}
这是问题的实现:
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>();
}
【问题讨论】:
-
请停止调用空字符串 ("")
null。它们不是空的,它们是空的。有区别。 -
是的,有区别。那么当你按下 Enter 时 Scanner 会得到哪一个呢?空字符串,还是 null?这是我的问题。
-
程序中的哪一行引发了
NullPointerException? -
这应该很容易在一个简单的 main() 方法中进行测试 - 调用 Scanner.nextLine() 并打印“null!”或“空!”取决于返回值
-
她没有调用空字符串
null。她原本以为nextLine()会为空行返回null,但后来决定它必须返回一个空字符串。
标签: java user-input while-loop