Question

I'm writing a program that is in a while-loop enters random numbers to a queue. When the queue is full, it writes it to a text-file and fills up the queue again. So far it is good, but what I want to do is for the while-loop to stop when the user enters the word "stop" in the console. How do I go about solving this? As you can understand, I know the method I'm using below is not working.

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");
                }
            }
        }
    }
}
Was it helpful?

Solution

Use do while for this..

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"));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top