用命令结束无限循环

时间:2014-04-28 09:49:59

标签: java arrays queue

我正在编写一个在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");
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分: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"));
相关问题