options for user input

38
Options for User Input Options for getting information from the user Write event-driven code • Con: requires a significant amount of new code to set-up • Pro: the most versatile. Use System.in • Con: less versatile then event-driven • Pro: requires less new code Use the command line (String[ ] args) • Con: very limited in its use • Pro: the simplest to set up

Upload: ismail

Post on 21-Jan-2016

19 views

Category:

Documents


0 download

DESCRIPTION

Options for User Input. Options for getting information from the user Write event-driven code Con: requires a significant amount of new code to set-up Pro: the most versatile. Use System.in Con: less versatile then event-driven Pro: requires less new code - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Options for User Input

Options for User Input

• Options for getting information from the user– Write event-driven code

• Con: requires a significant amount of new code to set-up• Pro: the most versatile.

– Use System.in• Con: less versatile then event-driven• Pro: requires less new code

– Use the command line (String[ ] args)• Con: very limited in its use• Pro: the simplest to set up

Page 2: Options for User Input

Using the command line

• Remember what causes the “big bang” in our programs?

Page 3: Options for User Input

Using the command line

• Remember what causes the “big bang” in our programs?

public static void main (String [] args) {

Page 4: Options for User Input

Using the command line

• Remember what causes the “big bang” in our programs?

public static void main (String [] args) {

• main expects an array of strings as a parameter.

• The fact of the matter is that this array has been a null array in each of our programs so far.

Page 5: Options for User Input

Using the command line

• However, we can give this array values by providing command line arguments when we start a program running.

Page 6: Options for User Input

Using the command line

• However, we can give this array values by providing command line arguments when we start a program running.

java MyProgram String1 String2 String3

Page 7: Options for User Input

Using the command line

• However, we can give this array values by providing command line arguments when we start a program running.

$ java MyProgram String1 String2 String3

args[0] args[1] args[2]

Page 8: Options for User Input

Using the command line

• We can use this to get information from the user when the program is started:

public class Echo {public static void main(String [] args) {

System.out.println(“args[0] is “ + args[0]);

System.out.println(“args[1] is “ + args[1]);} // end main

} // end Echo class

$ javac Echo.java$ java Echo Mark Fienupargs[0] is Markargs[1] is Fienup

Page 9: Options for User Input

What are some of the problems with this solution

• This works great if we “behave” and enter two arguments. But what if we don’t?

$ java Echo Mark Alan Fienupargs[0] is Markargs[1] is Alan

(no problem, but Fienup gets ignored)

$ java Echo Markargs[0] is MarkException in thread “main” java.lang.ArrayIndexOutOfBoundsException:

(Big problem!)

Page 10: Options for User Input

Fixing this problem• There are several ways to work around this problem

– Use Java’s exception handling mechanism (not ready to talk about this yet)– Write your own simple check and handle it yourself

public class MyEcho2 {

public static void main( String[] args ) {

if (args.length == 2) {

System.out.println("args[0] is ” + args[0]);

System.out.println("args[1] is " + args[1]);

} else {

System.out.println( "Usage: java MyEcho2 "

+ "string1 string2");

} // end if

} // end main

} // end MyEcho2

Page 11: Options for User Input

Fixing this problempublic class MyEcho2 {

public static void main( String[] args ) {

if (args.length == 2) {

System.out.println("args[0] is ” + args[0]);

System.out.println("args[1] is " + args[1]);

} else {

System.out.println( "Usage: java MyEcho2 "

+ "string1 string2");

} // end if

} // end main

} // end MyEcho2

$ java MyEcho2 Mark

Usage: java MyEcho2 string1 string2

$ java MyEcho2 Mark Alan Fienup

Usage: java MyEcho2 string1 string2

Page 12: Options for User Input

I learned something new!• Will this code work if the user types NO arguments:

“java MyEcho2”?

public class MyEcho2 {

public static void main( String[] args ) {

if (args.length == 2) {

System.out.println("args[0] is ” + args[0]);

System.out.println("args[1] is " + args[1]);

} else {

System.out.println( "Usage: java MyEcho2 "

+ "string1 string2");

} // end if

} // end main

} // end MyEcho2

Page 13: Options for User Input

Yes!

• The args array reference could be “null”, so doing args.length would cause an error!

• But it is not, since args is an array reference to an actual array with zero elements.

Page 14: Options for User Input

What about?public class TestArray {

public static void main( String[] args ) {

System.out.println("args.length = " + args.length );

String[] temp0 = {};

System.out.println( "temp0.length = " + temp0.length );

String[] tempNull;

System.out.println("tempNull.length=" + tempNull.length);

} // end main

} // end TestArray class

$ javac TestArray.java

TestArray.java:7: variable tempNull might not have been initialized

System.out.println( "tempNull.length = " + tempNull.length );

^

1 error

Page 15: Options for User Input

What about?public class TestArray {

public static void main( String[] args ) {

System.out.println("args.length = " + args.length );

String[] temp0 = {};

System.out.println( "temp0.length = " + temp0.length );

String[] tempNull = null;

System.out.println("tempNull.length=" + tempNull.length);

} // end main

} // end TestArray class

$ java TestArray

args.length = 0

temp0.length = 0

Exception in thread "main" java.lang.NullPointerException

at TestArray.main(TestArray.java:7)

Page 16: Options for User Input

Your turn to write a simple program using the command line

• Write a program to echo all command-line arguments to the System.out$ java EchoAll This is a long line

args[0] is This

args[1] is is

args[2] is a

args[3] is long

args[4] is line

Page 17: Options for User Input

Simple Calculations at Command Line

$ java Calculate 6 + 4

10

$ java Calculate 8 - 5

3

Page 18: Options for User Input

First Attempt - What’s wrong?public class Calculate {

public static void main( String[] args ) {

int operand1 = args[0];

String operator = args[1];

int operand2 = args[2];

if ( operator.equals("+") ) {

System.out.println( operand1 + operand2 );

} else if ( operator.equals("-") ) {

System.out.println( operand1 - operand2 );

} else {

System.out.println("Invalid operator: " + operator);

} // end if

} // end main

} // end Calculate

$ javac Calculate.java

Calculate.java:3: incompatible types

found : java.lang.String

required: int

int operand1 = args[0];

^

Page 19: Options for User Input

Correct Calculatepublic class Calculate {

public static void main( String[] args ) {

int operand1 = Integer.parseInt( args[0] );

String operator = args[1];

int operand2 = Integer.parseInt( args[2] );

if ( operator.equals("+") ) {

System.out.println( operand1 + operand2 );

} else if ( operator.equals("-") ) {

System.out.println( operand1 - operand2 );

} else {

System.out.println( "Invalid operator: "

+ operator );

} // end if

} // end main

} // end Calculate

Page 20: Options for User Input

The wrapper classes

• Primitive data types (int, double, boolean, etc.) are not actually objects. Because of this, you can’t use them easily in certain OO situations

• Because of that, java has “wrapper classes” such as Integer, Double, and Boolean.

• These are true classes in the OO sense of the word in that they contain data which store information (often the value in it’s corresponding primitive data type) and methods that can act on this data.

Page 21: Options for User Input

But wait a minute!

• How is it that we can use the parseInt() method without actually creating an instance of the Integer class.

Page 22: Options for User Input

Lifetime Modifiers

What does static mean?

Page 23: Options for User Input

Lifetime Modifiers

What does static mean?

• The item being declared is a feature of the class – what we usually call “class methods” or “class variables.”

• The item being declared exists at load time, before any instance is created.

Page 24: Options for User Input

Lifetime Modifiers

• A “class method” is one that can be invoked without sending a message to an instance of the class.

the main method of MemoPadApp

int operand1 = Integer.parseInt(args[0]);

double myRandom = Math.random();

Page 25: Options for User Input

Lifetime Modifiers

• A “class variable” is one that every instance has access to and shares.

In chapter 5, Budd creates windows in which bouncing balls live. Every instance of his BallWorld class shares the same height and width dimensions, implemented as static class variables:

public static int frameWidth=200;public static int frameHeight=250;

Page 26: Options for User Input

Lifetime Modifiers

• We will use these rarely in the code we write.– The more you use static stuff, the less flexible

and modifiable your code tends to be.

• The Java class library uses these more frequently. Budd will use them occasionally.– Thus, you will still get to see plenty of

examples before we are done!

Page 27: Options for User Input

Homework #2 - Implementing Constructors

• Goals for this assignment: practice implementing constructors

practice factoring common behavior into helper methods

experience working with command-line arguments

• You will continue to work with the MemoPad program for this assignment, including the database class that you implemented for Homework 1

Page 28: Options for User Input

Homework #2 - Task 11. Add a new constructor to your MemoDatabase class that

takes one argument: the maximum number of memos that can be stored.

The constructor should use this argument when initializing the size of the array in the constructor. The existing constructor should still use a default value for the array size. Notice that the constant now becomes the default maximum, not the actual maximum!

Test your new constructor by using it to create the database in the MemoPad class and then running the program. Verify that the database enforces the maximum size!

Make sure that the class's default constructor still works, too, and that it

still enforces its maximum number of entries.

Page 29: Options for User Input

Homework #2 - Task 22. Eliminate any code duplication in your MemoDatabase

class's constructors.

Your two constructors almost certainly have a lot of code common -- they do almost exactly the same thing! Make the duplication go away. One way to do that is to factor any common behavior into a private method named initialize.

Re-test both constructors by using them to create the database in the

MemoPad class and then running the program.

Page 30: Options for User Input

Homework #2 - Task 33. Add a new constructor to the MemoPad class that takes

one argument: the MemoDatabase that it uses to store

the memos.

In this constructor, use the argument to initialize the database instance variable.

Test your new constructor by using it to create the MemoPad in the

main() method and then running the program.

Page 31: Options for User Input

Homework #2 - Task 44. Change the original "default" constructor back to its

original form, from before Homework 1: initialize the

database variable to be a DefaultMemoDatabase.

Test the default constructor by using it to create the MemoPad in the

main() method and then running the program.

Page 32: Options for User Input

Homework #2 - Task 55. Eliminate any code duplication in the MemoPad

constructors.

The two constructors almost certainly have a lot of code common -- they differ in only one line! Make the duplication go away. One way to do that is to factor any common behavior into a private method named initialize.

Re-test both constructors by using them to create the MemoPad in the

main() method and then running the program.

Page 33: Options for User Input

Homework #2 - Task 66. Modify the main() method in the MemoPadApp driver to

accept up to two optional arguments that control the kind

of MemoDatabase to be used.

One optional argument is the choice of database class.

-d indicates to use the default implementation.

-s indicates to use the student implementation.

Page 34: Options for User Input

Homework #2 - Sample ExecutionsIf no argument is given, create a default

instance of MemoPad. For example:

$ java MemoPadApp

... MemoPadApp uses the default constructor of MemoPad

Page 35: Options for User Input

Homework #2 - Sample Executions• If the user specifies -d, create an instance of DefaultMemoDatabase and use it to initialize the MemoPad you create. For example:

$ java MemoPadApp -d

... MemoPadApp creates a DefaultMemoDatabase and passes it to MemoPad's constructor

Page 36: Options for User Input

Homework #2 - Sample Executions• If the user specifies -s, then the command-

line may contain a second optional argument, an integer to specify the maximum number of entries in the database.

• Use this integer to create an instance of your database class. If no second argument is given, create a default instance of your array-based database class. In either case, use this database object to initialize the MemoPad you create.

Page 37: Options for User Input

Homework #2 - Sample Executions

$ java MemoPadApp -s

... MemoPadApp creates an instance of your MemoDatabase (use default constructor) and passes it to MemoPad's constructor

$ java MemoPadApp -s 100

... MemoPadApp creates an instance of your MemoDatabase (use the int constructor) and passes it to MemoPad's constructor

Page 38: Options for User Input

Homework #2 - Sample Executions

• If the user gives any other command-line argument, print an error message and return without creating any objects. For example:

$ java MemoPadApp -oops

Usage: java MemoPadApp

java MemoPadApp -d

java MemoPadApp -s [size]