[英]Why can I not let my program run my method over and over (while loop)?
这是一个日记程序,可让您在日记中写东西(很明显)。 输入回车并按回车后,页面将关闭,并将其保存在列表中。 我的问题是,只有我拥有Pages()时,它只能运行一次; 在main方法中,所以我尝试了这个循环。 它对我不起作用,我也不知道为什么。 需要一些帮助
import java.util.ArrayList;
import java.util.Scanner;
public class NotizbuchKlasse{
public static void Pages() {
System.out.println("day 1 : Write something in your diary.");
System.out.println("Write enter if you are done writing.");
ArrayList<String> List = new ArrayList<String>();
String ListInList;
Scanner write = new Scanner(System.in);
do {
ListInList = write.next();
List.add(ListInList);
} while (! ListInList.equals("enter"));
List.remove(List.size()-1);
write.close();
System.out.println("This is now your page. Your page is gonna be created after writing something new.");
System.out.println(List);
}
public static void main(String[]Args){
boolean run = true;
do{
Pages();
} while(run);
}
}
错误:
This is now your page. Your page is gonna be created after writing something
new.
Exception in thread "main" [hello]
day 1 : Write something in your diary.
Write enter if you are done writing.
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at NotizbuchKlasse.Pages(NotizbuchKlasse.java:12)
at NotizbuchKlasse.main(NotizbuchKlasse.java:24)
阅读之前,需要检查是否有要阅读的东西。 您当前不是,这就是为什么您遇到NoSuchElementException
的原因。
您可以通过Scanner
的has*
方法执行此操作。
例如:
ArrayList<String> List = new ArrayList<String>();
Scanner write = new Scanner(System.in);
while (write.hasNextLine()) {
String ListInList = write.nextLine();
if (ListInList.equals("enter")) break;
List.add(ListInList);
}
// No need to remove the last item from the list.
而且,我注意到您的main
方法中有一个循环,您在该循环中调用Pages()
。 如果您关闭write
,那么您还将关闭System.in
; 流关闭后,您将无法重新打开它。 因此,如果您下次尝试从System.in
读取内容,则在下次调用Pages()
,流已关闭,因此没有任何要读取的内容。
只是不要调用write.close()
。 您不应该关闭通常没有打开的流; 并且您没有打开System.in
(JVM在启动时就打开了),因此请不要关闭它。
您想使用如下的while循环:
while (write.hasNextLine()) {
ListInList = write.nextLine();
if (doneWriting(ListInList)) { // Check for use of enter.
break; // Exit the while loop when enter is found.
}
List.add(ListInList); // No enter found. Add input to diary entry.
}
其中doneWriting()
是一种方法(由您编写!),该方法检查用户是否键入enter
。
这是 Scanner的next()
方法的文档 。 如果您阅读了它,将会发现它在令牌用尽时会引发异常。
如果您想要更多一点随意的解释, 这是先前询问的关于next()
和nextLine()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.