gpt4 book ai didi

java - 为什么我不能让我的程序一遍又一遍地运行我的方法(while 循环)?

转载 作者:行者123 更新时间:2023-12-01 17:55:39 24 4
gpt4 key购买 nike

这是一个日记程序,它允许您在日记中写一些东西(显然)。输入 Enter 并按 Enter 后,页面将关闭,并将其安全地保存在列表中。我的问题是,当我有 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 的原因。

您可以通过 Scannerhas* 方法来执行此操作。

例如:

    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;一旦流关闭,您就无法重新打开它。因此,如果您下次调用 Pages() 时尝试从 System.in 读取内容,则流已关闭,因此没有任何内容可读取。

只需不要调用write.close()。您不应该关闭通常没有打开的流;并且您没有打开 System.in(JVM 在启动时打开了),所以不要关闭它。

关于java - 为什么我不能让我的程序一遍又一遍地运行我的方法(while 循环)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45123101/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com