Last modification: 17/10/2016
Reversed lines.
Write a program that reads as much lines from the standard input as as it can. Then it writes the lines to the standard output in reverse order. Use a java.util.LinkedList<A>
object in order to store the lines.
Note:
Hit Ctrl-D
(on Linux) or Ctrl-Z
(on Windows) to signal that there are no more lines to read.
Use a java.util.Scanner
object and its hasNextLine()
method in order to check for lines available to read. You can read the next line using the nextLine()
method.
Simplified cat
.
Create a simplified version of cat
of the Unix-like systems. Cat
takes a filename as argument and writes its contents to the standard output.
Example:
$ echo "Hello, World!" > hello.txt
$ java Cat hello.txt
Hello, World!
Simplified grep
.
Create a simplified version of grep
of the Unix-like systems. Grep
takes string and a filename as arguments.
It prints the lines which equal the string argument from the file to the standard output.
It prints the lines which contain the string argument from the line to the standard output.
Extra exercise. It also prints out the number of the line in which the string argument is found. Use a java.io.LineNumberReader
to obtain the current line’s number.
Example:
$ echo "Hello, World!\n Howdy?" > hello.txt
$ java Grep World hello.txt
Hello, World!
The program should be able to handle the case when the file cannot be found by catching java.io.FileNotFoundException
.
It may not catch java.io.IOException
but it must be specified in the signature of main()
.
The program should guarantee that the file is closed after reading in all cases.
Average of grades. Extra exercise.
Create a program that computes the average of grades of a given student. The program takes the name of the student and a filename as arguments. The grades are read from the file. Every line consists of a name and equal number of grades, however the number of grades is not known in advance. We assume that the lines are in correct format.
Example:
$ cat grades.txt
Brian: 4 3 5 4 5
Peter: 4 2 5 1 3
Adam: 5 4 5 3 4
$ java Avg "Peter" grades.txt
3.0
$ java Avg "Smith" grades.txt
$ java Avg "Adam" asd
File not found!
Text files in a directory. Extra exercise.
Create a program that lists the names of all text files (having .txt
extension) in a given directory.
Example:
ls -l Documents/
articles/
books/
notes.txt
Program.java
thesis.pdf
todo.txt
$ java ListTxt "Documents/"
notes.txt
todo.txt