Question: CS 1113 LAB #9: Input and Output Methods Lab Goals The goal of this lab is to help you understand different input and output methods.
CS 1113LAB #9: Input and Output Methods
Lab Goals
The goal of this lab is to help you understand different input and output methods. The main input methods covered by the lab are:
1) Using a Scanner to read input from the keyboard2) Using a Scanner to read redirected input3) Creating a Scanner to read from a file given the file name
The output methods covered in this lab are:
1. Writing to a file using redirection2. Opening a file and writing to it using PrintWriter
Motivation
Being able to accept input in multiple ways, process it, and provide output in multiple ways is an important skill. We have already seen some ways to get input to a program and write output, but we have not done a comparative study of different input and output methods. The purpose of this lab is to do such a study, and give you a toolbox of input and output methods for working with the console and text files. __________________________________________________________________________________________
Directions
Go through the lab below. Make sure to copy files as directed, since you will have to turn in the different versions you create with the lab. Write out the answers to questions numbered with a Q in the text file lab9answers.txt and turn that in with your lab as well. Write your name at the top of this file.
Command line input and output
Using command line arguments is one of the more efficient ways to interact with a console program. It allows you to type in the data needed by a program without waiting to be prompted. It also allows your program, along with its parameters, to be repeated and scripted easily.
Part 1) The program listed below reverses a string that is input on the command line. Type in or copy the program, changing to the comments to reflect your name and section.
// ReverseCL
//
//
public class ReverseCL
{
public static void main(String[] args)
{
String s = args[0];
String rev = "";
for (int i=0; i { rev = s.charAt(i) + rev; } System.out.println(rev); } } Part 2) Now compile and run ReverseCL with a string argument of Hello: java ReverseCL Hello Note that this mode of input is given to you essentially for free. The input itself is separated into tokens and passed directly to the main method. The programmer does not have to do anything special to get it. Usage StatementPart 3) Now run ReverseCL with no parameters, issuing the command: java ReverseCL Q1: What happened? _________________________________________________ReverseCL has the problem that it will crash if there are no command line arguments, giving an ArrayIndexOutOfBounds exception. Part 4) Copy ReverseCL.java to ReverseCL2.java, changing the anme of the class to ReverseCL2. Make sure to include your name and section number in the comments. Add a usage statement that tells the user how to use the program when no command line arguments are given. The idea is to assume that if a user invokes a command without any parameters, they are looking for directions about how to use the command. This is how Unix utilities and many other command line applications work. For example, if you type javac on the command line, you will get a usage printout, along with a list of optionsin essence, a tiny manual of how to use the application: Usage: javac where possible options include: -g Generate all debugging info -g:none Generate no debugging info -g:{lines,vars,source} Generate only some debugging info ... Part 5) Now, compile and run ReverseCL2.java without any command line arguments. Q2) What message did your program print you print?Parsing Numbers Part 6) Copy ReverseCL2.java to AddNumbers.java. Change the class name to AddNumbers, and change the program so that it adds two integers together that were given on the command line. Also, change the usage statement to something appropriate. Q3) How did you change the program to convert the inputs to ints? Using a Scanner with the keyboard. Part 7) A second way to get input is to prompt the user, and employ a Scanner. Copy ReverseCL2.java to a new class called ReverseKeyboard.java, and change the name of the class to ReverseKeyboard. Now, get rid of the usage statement, and replace the line String s = args[0]; with code that (1) declares a Scanner that takes input from the keyboard, and (2) asks the user for a string input that you put into a String variable called s. Compile and run your program. Q4) What lines of code did you add?Part 8) Run ReverseKeyboard to make sure it works. Redirecting Input and output from a File Redirection allows a program to receive input from a file as though it had come from the keyboard. This is powerful for several reasons. One reason is that the programmer can use a single method to read from files or the keyboard. An even more interesting reason is that redirection allows a single program to act in two different ways without having to handle multiple input modes explicitly. Input can be redirected from a file by using the < symbol, as in the following: java MyClass < input.txt In this case, the input source for System.in is changed from the keyboard to the specified file.Q4) What command would you use to run the class MyClass, using input2.txt as the input source? When used on the command line, the greater than symbol > redirects the output, so that things printed to System.out will go to a file instead of the console, as in the following: java MyClass > output.txt Input and output redirection can be used together on the same command line. Q5) What command would you use to run MyClass, hooking up input.txt as the input source, and output.txt as the output destination? Part 9) To practice redirection, we will need a test file. Create a file called lab9.txt with the word Reverse in it, and nothing else. Part 10) Redirection of input can be done on the command line using the < option. Run the following command: java ReverseKeyboard < lab9.txt Q6) What was printed? Notice that the program did not wait for you to type input, even though it printed the prompt asking for input. Now let's try to redirect the program's output. We can do this using the > option. Part 11) Run the following commandjava ReverseKeyboard < lab9.txt > lab9a.txt If this worked, nothing should have been printed on the command line, but the file lab9a.txt should have been created. Q7) What are the contents of lab9a.txt? Notice that both the user prompt and other output was written to lab9a.txt. This demonstrates the fact that input redirection has limitations. For example, if a program must interleave reading input from two different files, simple redirection will not work. Opening a file based on the command line argument with Scanner Yet another common input form is to have the user specify the name of an input file on the command line. The file can then be opened with a Scanner. To read from the file "input.txt", you would create a scanner as folows: Scanner input = new Scanner(new File("input.txt"));Q8) How would you instantiate a Scanner to read from a file if the file name is held in a String called fileName? Using try-catch when working with files When you instantiate a Scanner using a file as the input stream, the file may not exist, or you may not be allowed to open it for some reason. When this happens, an error, called an "Exception", is generated. Because of this, the code that instantiates these must be placed in a try-catch. You will see this in the Interleave class in the next part. Part 12) Finish the following program Interleave.java that interleaves the lines of two different input files that are given on the command line: // Interleave // // import java.util.*; import java.io.*; public class Interleave { public static void main(String[] args) { // Usage statement (2 inputs needed) // [Add code here] try { // Open scanner for file named args[0] Scanner scan1 = new Scanner(new File(args[0])); // Open scanner for file named args[1] // [Add code here] boolean moreLines = true; while (moreLines) } } // If scan1 has another line then read that line, copy it // to the console, and set moreLines to true // [Add code here] // If the second scanner, scan2, has another line, // then get that line, copy it to the console, and set // moreLines to true. // [Add code here] { moreLines = false; catch (IOException ex) { // [Add code here] } } } Part 13) Compile and run Interleave.java, using lab9.txt and lab9a.txt as input. When you are satisfied that it works, redirect the output to lab9b.txt. Writing to files based on the command line argument PrintWriter As with input, sometimes output cannot be done easily through redirection. For example, if your program needs to interleave writing to two different files, redirection will not work. In this case, we can use a PrintWriter. PrintWriter allows you to send output to a file in a way that is very similar to using System.out. Once opened, you can write to the file using the methods print, println, and printf, just as with System.out. For example: PrintWriter writer = new PrintWriter(new File("output.txt")); writer.println("hello"); Q9) What code would you use to write an integer variable n to a PrintWriter called writer? Part 14) Finish the following program SplitFile.java below that does the opposite of Interleave. That is, it takes as input one file, and writes out interleaved lines to two different files. In this case, all three file names will be given on the command line. // SplitFile // // import java.util.*; import java.io.*; public class SplitFile { public static void main(String[] args) { // Usage statement (3 inputs needed) // [Your code here] PrintWriter file1 = null; PrintWriter file2 = null; try { // Open Scanner for file named args[0] Scanner scan = // [Add code here] // Open a PrintWriter for file named args[1] file1 = new PrintWriter(new File(args[1])); // Open a PrintWriter for file named args[2] file2 = // [Add code here] while (scan.hasNextLine()) { // Read a line from scan // Write that line to file1 // [Add code here] if (scan.hasNextLine()) { } } // Read a line from scan // Write that line to file2 // [Add code here] } // Catch the IOException // [Add code here] // Create a finally block that closes the two PrintWriters // Add code here } } Part 15) Make a test file for SplitFile with a few lines in it. Call the file lab9c.txt. The file should have multiple lines of text. Compile and run SplitFile, using lab9c.txt as input, and lab9d.txt and lab9e.txt as output. java SplitFile lab9c.txt lab9d.txt lab9e.txt Part 16) Hand in your lab to D2L. You should have the following files: lab9a.txt lab9b.txt lab9c.txt lab9d.txt lab9e.txt lab9answers.txt ReverseCL.java ReverseCL2.java ReverseKeyboard.java Interleave.java SplitFile.java
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
