Write a queue client, "LineNum," that takes an integer command line argument “n” and prints the nth string from the first string found on standard input. [MO6.2]
Please note that you would need to use a queue to implement it for full credit. You should add the strings inputted by the user to a queue using the enqueue method. Then you should remove and return "n" strings from the queue using the dequeue method. The nth string that is returned by the dequeue method should then be printed out.
Code -
import java.util.*;
public class LineNum {
public static void main(String[] args) {
//read command line arguement from user
int n = Integer.parseInt(args[0]);
//initialize a queue
Queue<String> elements = new
LinkedList<>();
//using try catch to read user input and when user
press CTRL+D it will exit
try {
//byter array to store user enter data
byte[] byteArray = new byte[1024];
//continue for loop till user enter CTRL + D
for (int i; (i = System.in.read(byteArray)) != -1;) {
//convert the byteArray to string
String userInput = new String(byteArray, 0, i);
//add the element to the queue
elements.add(userInput);
}
} catch (Exception e) {
e.printStackTrace();
}
//dequque element till the n - 1
for(int i = 0 ;i < n-1; i++){
elements.remove();
}
//print the peek element
System.out.println(n+" from the first is
"+elements.peek());
}
}
Input ->
java LineNum 3
this
is
not
a
shorter
version
CTRL + D
3 from the first is not
Output -
Get Answers For Free
Most questions answered within 1 hours.