Write a customizable randomizer.
Concepts: command line arguments; file I/O
Write a program that reads in a file and displays a random line of that file. This could be used for a number of uses--as a die roller, to display random quotes, etc. Here are a couple sample files for use as a die roller: d6.txt and d20.txt. Feel free to create your own input files too.
Your program should take at least one filename as a command line argument. This is the file to open and read. If no command line arguments are given (or more than 2), give an error message and explain how to use the program properly.
If a second command line argument is given, treat this as the name of a log file. Your program should append to this log file whatever line it prints to the screen.
Your program should catch all exceptions and explain the source of the error. IOExceptions are pretty good at explaining their cause: call the
To test your program, try opening a file that doesn't exist or writing to a file that's in use by a program that locks its files while editing them (such as MS Word).
D:\TA\grading\A17>java ZtomaszeA17 No filename (or too many) specified on command line. Usage: java ZtomaszeA17 inputfile [outputfile] This program displays a random line from inputfile. If outputfile is also given, it also appends the random line to that file. D:\TA\grading\A17>java ZtomaszeA17 d20.txt 4 D:\TA\grading\A17>java ZtomaszeA17 d20.txt 2 D:\TA\grading\A17>java ZtomaszeA17 d20.txt 10 D:\TA\grading\A17>java ZtomaszeA17 d20 Could not open file: d20 (The system cannot find the file specified) D:\TA\grading\A17>java ZtomaszeA17 d20.txt log.txt 13 D:\TA\grading\A17>java ZtomaszeA17 d20.txt log.txt 20 D:\TA\grading\A17>more log.txt 13 20 D:\TA\grading\A17>java ZtomaszeA17 d20.txt log.txt Could not open file: log.txt (The process cannot access the file because it is being used by another process)
This last line generated an exception because I had opened log.txt in another program that locks the files it opens. While log.txt was in use by that other program, I tried running my program and writing to the file--hence the exception.
What to submit
Out of 5 points:
|~ztomasze Index :
TA Details: ICS111:
|Last Edited: 11 Nov 2008|
©2008 by Z. Tomaszewski.