[英]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.