【问题标题】:end infinite loop with command用命令结束无限循环
【发布时间】:2014-04-28 09:49:58
【问题描述】:

我正在编写一个处于 while 循环中的程序,它将随机数输入到队列中。当队列已满时,它会将其写入文本文件并再次填满队列。到目前为止它很好,但我想做的是当用户在控制台中输入单词“stop”时,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");
                }
            }
        }
    }
}

【问题讨论】:

  • 您将InputStreamString 进行比较

标签: java arrays queue


【解决方案1】:

为此使用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"));

【讨论】:

  • 谢谢,但这并不能完全解决问题。我可以通过输入 stop 来取消循环,但现在它不会向我的文本文件写入任何内容。
猜你喜欢
  • 2013-09-30
  • 2014-12-12
  • 1970-01-01
  • 1970-01-01
  • 2015-09-05
  • 2017-06-11
  • 1970-01-01
  • 2017-11-16
  • 2020-04-21
相关资源
最近更新 更多