gpt4 book ai didi

java - 用命令结束无限循环

转载 作者:行者123 更新时间:2023-12-01 13:04:57 25 4
gpt4 key购买 nike

我正在编写一个程序,该程序在 while 循环中将随机数输入到队列中。当队列已满时,它将其写入文本文件并再次填充队列。到目前为止,一切都很好,但我想做的是当用户在控制台中输入“停止”一词时让 while 循环停止。我该如何解决这个问题?正如您所理解的,我知道我下面使用的方法不起作用。

public static void main (String [] args) throws IOException{
DataBuffert theBuffert = new DataBuffert(10);
Random random = new Random();
DataOutputStream logFile = new DataOutputStream(new FileOutputStream("logfile.txt"));

while(!System.in.equals("stop")){
theBuffert.enqueue(random.nextInt(500));
if (theBuffert.isFull()){
while (!theBuffert.isEmpty()){
logFile.writeBytes(String.valueOf(theBuffert.dequeue()+"\n"));
try {
Thread.sleep(1000);
} catch(InterruptedException ex) {
System.out.println("Operation interrupted");
}
}
}
}
}

最佳答案

为此使用do while..

String check=""; 
Scanner scan=new Scanner(System.in);
do{
theBuffert.enqueue(random.nextInt(500));
if (theBuffert.isFull()){
while (!theBuffert.isEmpty()){
logFile.writeBytes(String.valueOf(theBuffert.dequeue()+"\n"));
try {
Thread.sleep(1000);
} catch(InterruptedException ex) {
System.out.println("Operation interrupted");
}
}
}
check=scan.next();
}while(!check.equals("stop"));

关于java - 用命令结束无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23337800/

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