Write a java program called Queues.java to simulate the operation of an I/O buff
ID: 670444 • Letter: W
Question
Write a java program called Queues.java to simulate the operation of an I/O buffer using a linked queue data structure. Queues are used extensively in situations where the input or output has to be delayed because of, for example, slow Internet speeds - these queues are called I/O buffers. Built-in Java data structures may be used.
The program must accept a sequence of lines of text from the keyboard and process them as follows:
If the first character is O (Oh), extract the next string from the buffer and output it. If there is no data in the queue, output "Buffer empty"
If the first character is X, exit.
Otherwise, store the string in the buffer.
Sample Input/Output
line1
line2
O
Data: line1
line3
line4
O
Data: line2
O
Data: line3
line5
O
Data: line4
O
Data: line5
O
Buffer empty
X
Explanation / Answer
ioBuffer.java
import java.util.Scanner;
class ioBuffer{
public static void main(String[] args){
Scanner read = new Scanner(System.in);
Queue myQueue = new Queue();
String inp = "";
while((inp = read.nextLine()).charAt(0) != 'X'){
if(inp.charAt(0) == 'O'){
System.out.println( myQueue.deQueue());
}
else{
myQueue.enQueue(inp);
}
}
}
}
class Queue{
private int N;
private Node first;
private Node last;
private class Node{
private String data;
private Node next;
}
public Queue(){
N =0;
first = null;
last = null;
}
public boolean isEmpty(){
return (first == null);
}
public void enQueue(String data){
Node temp = last;
last = new Node();
last.data = data;
last.next = null;
if(isEmpty()){
first = last;
}
else{
temp.next = last;
}
N++;
}
public String deQueue(){
String temp = "";
if(!isEmpty()){
temp = "Data: " + first.data;
first = first.next;
N--;
}
else if(isEmpty()){
last = null;
temp = "Buffer Empty";
}
return temp;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.