Write a customizable randomizer.
Concepts: command line arguments; file I/O
Textbook: 7.4; 10.6
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 and hitLocations.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 getMessage()
method on the exception you caught to get details you can pass on to your human user.
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\A18>java ZtomaszeA18 No filename (or too many) specified on command line. Usage: java ZtomaszeA18 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\A18>java ZtomaszeA18 d20.txt 4 D:\TA\grading\A18>java ZtomaszeA18 d20.txt 2 D:\TA\grading\A18>java ZtomaszeA18 d20.txt 10 D:\TA\grading\A18>java ZtomaszeA18 d20 Could not open file: d20 (The system cannot find the file specified) D:\TA\grading\A18>java ZtomaszeA18 d20.txt log.txt 13 D:\TA\grading\A18>java ZtomaszeA18 d20.txt log.txt 20 D:\TA\grading\A18>more log.txt 13 20 D:\TA\grading\A18>java ZtomaszeA18 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.
Upload your UsernameA18.java
file to Tamarin.
try { Scanner filein = new Scanner(new File("input.txt")); while (filein.hasNextLine()) { System.out.println(filein.nextLine()); } }catch (FileNotFoundException fnfe) { System.out.println("Could not open file: " + fnfe.getMessage()); }
Math.random()
to grab a random line from the list.
When given two arguments, your program does essentially two things: prints a random line from one file, and writes that line to the second file. It's a question of design whether or not it should do the first thing if it is not going to be able to do the second thing. Either design choice is fine.