CSE1020 Lab 02

Part 1: Simple Input from the Command Line

Part 1 shows you one way for your programs to accept user input.

You should be able to complete Part 1 in 15 minutes or less.

Create a lab directory

Use the techniques you learned from the Guided Tour to create a suitable directory for this lab and start jEdit. You might consider opening a terminal and entering the following commands:

cd Documents/cse1020
mkdir lab02
cd lab02
jedit &

 

Create a class named IntInput

This class will show you how your program can read two integers from the command line when it is run. Start your program in the usual way as shown below.

Remember that you must save your program as IntInput.java

 

 

Using Integer.parseInt

Your program will expect that a user will always supply two integers on the command line when the program is run. For example, a user might run your program like so:

java IntInput 10 20

where the numbers 10 and 20 are called command line arguments (individual arguments are separated by spaces).

A Java program has access to the command line arguments through the array args in the main method. The command line arguments are passed to your program as Java strings.

The first command line argument can be accessed using the notation args[0], the second can be accessed using args[1], and so on.

In this particular case, we want the command line arguments to be integers, but Java supplies them as strings. You can convert a String to an int using the method Integer.parseInt as shown below.

 

 

Output

For this small example program, we will simply output the command line arguments as part of a sentence as shown below.

Notice that you can print the int values stored in first and second (i.e., you can print anything, not just strings).

 

 

Run

Save, compile, and debug your program if necessary.

Try running your program in the following ways and observe what happens:

 

java IntInput 10 20
java IntInput 20 10
java IntInput
java IntInput 100

 

print or println

Do you understand the difference between print and println?

Modify your program by changing every instance of

out.print

to

out.println

Save, compile, and run your program and observe the difference.

 

Submit

Submit your program using the command:

submit 1020 L02 IntInput.java

and proceed to Part 2.