CA04 Tail application
Question 1
Give the output printed byjava Stackfor the following input:
it was - the best - of times - - - it was - the - -
Question 2
What does the following code fragment print when N is 50? Use a program trace, like slide 14, to confirm that the output is correct. Give a high-level description of what it does when presented with a positive integer N.
// Mystery code - what does it do?
// Not a great stack implementation - rewrite using a Deque instead. For details, see
// https://docs.oracle.com/javase/7/docs/api/java/util/Stack.html
//
import java.util.Stack;
public class Scratch {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
Stack stack = new Stack();
while (N>0) {
stack.push(N%2);
N = N / 2 ;
}
for (int d: stack) System.out.println(d);
}
}
Question 3
A popular way to implement queues using thejava.utilpackage is to use the
Queueinterface. Write an application calledTail, that prints the lastkstrings found on the standard input (assuming the standard input haskor more strings), using theQueueinterface.
- The user should be able to typejava Tail 20
- Download the text files provided, into your workspace folder. Test the program with each text file.
- Deliverables:
- one single .java file, properly commented.
- One short report, containing the usual sections:
- problem spec (and description of tests)
- Design (a UML activity diagram and class diagram)
- Test results, showing that the program passed the tests described in sec 1.
Below are some interesting code snippets that you might find useful. Before writing your own application, copy, paste and run the snips below, and make sure they work for you
An ArrayBlockingQueue:
// ArrayBlockingQueue demo
import java.util.concurrent.ArrayBlockingQueue;
public class TailSample {
public static void main(String[] args) {
ArrayBlockingQueue abq = new ArrayBlockingQueue(5);
abq.add( new String("Hello") );
abq.add( new String("Hithere") );
abq.add( new String("Goodbye") );
System.out.println("ArrayBlockingQueue:" + abq);
}
}
Scan one word at a time from a file:
// scan one word at a time
import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
public class TailSample {
public static void main(String[] args) {
// open a text file for reading
Scanner sc;
try {
sc = new Scanner(new File("tinytinyTale.txt"));
while (sc.hasNext() ) {
String s = sc.next();
System.out.println("[ " + s + " ]" ) ;
}
sc.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}