Java Reference
In-Depth Information
Lab 1.2: Using Command-Line Arguments
When you run a Java program from the command prompt, you can input
arguments that get passed to the main() method as strings. For example,
suppose that you entered the following command to run your Signature
program from Lab 1.1:
java Signature hello 27 “Rich Raposa”
This command has three command-line arguments beyond the java
Signature command: hello, 27, and Rich Raposa. (Arguments are sepa-
rated by spaces unless placed in double quotes.) These three arguments
are passed into main() and placed in the args parameter. The args param-
eter is an array of strings that can hold as many command-line arguments
as you enter.
To access these arguments within main(), you use args with a subscript
in square brackets. For example, args[0] is the first argument, args[1] is
the second, and so on. In the current example, args[0] will be the string
“hello,” args[1] will be “27,” and args[2] will be “Rich Raposa.”
In this lab, you will display the title and author of a topic, where the
title and author are entered as command-line arguments such as:
Title: Green Eggs and Ham
Author: Dr. Seuss
Now, follow these steps:
1. Create a new subdirectory of javafiles, called Lab1_2.
2. Open your text editor, and write a public class called Book.
3. Add main() within your Book class.
4. The title will be args[0] and the author will be args[1]. You need to
concatenate “Title: “ with args[0], which is done by using the + oper-
ator. For example:
System.out.println(“Title: “ + args[0]);
5. Similarly, use the concatenation operator to display “Author: “ and
args[1].
6. Save your Book class in the Lab1_2 directory in a file called
Book.java.
Search WWH ::




Custom Search