More Classes and Input



Classes Objects and Input

Additional topics on Classes using Strings.

Introduction to Input using JOptionPane.

Exercise 3

Prerequisite:

1. Read Sections 2.4 through 2.7, 2.9 and 3.1, 3.2, 3.3

2. Exercise 1 and 2. All questions answered and practice exercises completed

3. Read this document first and Appendix A on page and Appendix B on page before doing this exercise.

4. You will not be able to complete this exercise by reading this document alone. All Exercises will be required for completion of project 1 and the final project.

Built in Classes and pre-defined Methods in Java

The String Class:

The String class is another data type often needed in programming. What makes this data type very much different from the Primitive Data Types learned in the previous exercises is that the String data type is a built in class. The string class is just like every other class in Java; they contain both attributes and methods. The String class can “store and process strings of characters”[?]. The data that is stored in a String are a group of characters and the size of the String is determined by the number of characters it contains. For example:

Example 1: The use of a String.

The String Name in the example above contains 11 characters placed in between the double quotes. These 11 characters are stored into memory labeled or identified by the word Name. Due to the nature of the data type String, the size of the String can grow as characters are added to the end. Adding characters to the end of a string is called string concatenation. For Example:

Example 2: String Concatenation

The above example will yield the string “Bob O’reily is here” in the String labeled Message. Using the + operator with a String identifier allows the programmer to add more characters to the end of the string. From this observation it can now be made that the + operator in Java has a dual purpose. One is to perform Arithmetic on Primitive data types like int or double. The other is for String concatenation[?]. You can concatenate both Strings and Primitive Data Types to the end of a String[?].

The methods of the String class will be learned as each student has the chance to use them in a written program. This is true with many of the topics that have been discussed thus far. One example of a method that is quite usefule in the String class in the charAt() method.

The charAt() method of the String class returns a character of a string at a specific location. The location of the character is passed as an integer to the charAt() method in the parameter list. Each character in a String is located in a specific location and the location of the character is often referred to as the String index. The String index starts at 0 and ends at the last character of the String. For Example:

[pic]

Example 3: The use of the charAt() method[?]

You can notice in each of these examples an instance of the String class must be created in order to store information in the String and use the built in methods. This is true with the charAt() method and ALL methods of the String class.

The Math Class

The Math class is very different from the String class. Both classes have attributes and methods and share some common characteristics that are relevant to all classes in Java. The difference is that the Math class can be used in a program without creating an instance of the class[?].

The Math class groups mathematical methods together in one class. This includes methods such as sqrt(), pow(),sin(), etc. These are methods that are used for more complex math computations that the basic operators in Java cannot perform. As the student progresses through the year he/she will learn more of these methods and how to use them[?]. The basic use of the class and the methods that are associated with it is straight forward and fairly simple. For Example

Example 4: The use of the Square root Method

in the Math class.

In the previous example, Answer will contain the number 3 which is the square root of 9.

With the use of the Math class methods and the Basic operators provided with the Java language, a programmer can write programs that can solve fairly complex Mathematical problems.

Getting input from the user

By now you should know that output is provided to the user through the console with the use of the method System.out.println(). Wouldn’t be easy if we could get input from the user with the method System.in.keyboard()? Well you can’t. Getting input from a user in Java is not an easy task to do[?].

For one ALL input received to a program is in the form of a String[?]. This means that the programmer needs to keep this in mind when the program is requiring an input of an integer or real number. The String that holds the input from the user requires to be converted to the expected data type.

Java does not provide an easy class or method to use for the console to get input from the user from the system console[?]. Java does, however provide a means to get input from the user from a “Pop Up” dialog box. This is accomplished with using the JOptionPane object and it’s methods in the Java swing library[?].

JOptionPane

In order to use the JOptionPane input dialog box the programmer needs to import the Java swing library at the top of every class he/she wishes to use input. This is used with the Java keyword import followed with the library needed[?].

Once the library is included in the class, the programmer can then use the statement JOptionPane.showInputDialog() to display a blank dialog box for user input. The “metod showInputDialog() is a class method that displays dialog windows and returns data typed into them”[?] as a String to the calling method. For Example:

Example 5: This example illustrates the use of JOptionPane

From the above example an Input Dialog box will appear and prompt the user to enter a word. When the user enters a word, the string is then placed into the variable called U_Input. It is important to note again, ALL input received or returned from the Input Dialog box is a String.

What about other data types like int? When an integer or other primitive data type is required from the user, it must be converted from a String to the expected data type (i.e. int). To convert a String to the int data type, the method Integer.parseInt(U_Input) can be used. The method Integer.parseInt(U_Input) will convert the String stored in U_Input to an integer and return this integer to the calling method. For Example

Example 7: This illustrates how to use the Integer.parseInt() method to get an integer from a string.

From this example you can see that the user is asked with the Input Dialog box to enter there height. This input from the user is in the form of a String and is stored in the U_Input String. The integer value of the String is converted when the U_Input String is passed to the method Integer.parseInt(). The Method Integer.parseInt() then returns the integer value and stores it in the integer named height.

You can accomplish the same result for converting a String to a double with the use of the method Double.parseDouble(). This method is used exactly in the same manner as Integer.parseInt(), with the result returned as a double and not an int.

A Closer look at methods in Java

In the main implementation or Application class file, you should have noticed that in this class there is a very important method. This method of course is called the main method and this is where the execution of ALL programs in Java begins. The order of execution of the program begins and ends with this method in a Java program. With out it, the program will not execute.

The main method follow the same rules as the other methods mentioned thus far with some exceptions.

1. It must be public

2. It must contain the parameter String[] args in the parameter list

3. It must have a return type of void (for now)

4. It must have the name main.

5. May not be overloaded.

Besides this, the main method functions in the same way as all other methods in a Java program.

Method overloading

Method overloading is when you have two methods in a class with the same name. There is a distinction between the two methods and this is the parameters that the method may accept.

Overloaded methods are methods in a class that have the same name but different parameter lists. The parameter list may be different in the number of parameters as well as the types that the method will accept. They do not differ, however, by the return type. For Example, please see the overloaded method in the Appendix on page 11 called setMessage().

From this example you can see that the first method setMessage() contains no parameters and calls on JOptionPane to set the value of the String theMessage. The second setMessage() method accepts one parameter and sets theMessage to the parameter passed to it. The implementation of the overloaded method is determined by the way that the method is called. For Example in main you may have something like:

Example 8: This example illustrates how to call overloaded methods from main

The above example shows that the program will execute the method not only by its name, but also by the parameters that are passed. This means that when the program executes, it looks for the method by its name and then examines the parameters that are required to execute the method.

Observations:

You can clearly see the use of many of the built in classes and methods in the Java language. The usefulness of the String and Math class in computer programming as well as the JOptionPane class.

Lab Exercise

Write a program that will accept input from the user the following.

1. His/Her name.

2. Their Age

3. Their Height

4. Their Major

5. Their GPA

The program will then output to the user all the information that the user entered. You will have one class and the class will contain the following Attributes

1. Age

2. Name

3. Height

4. Major

5. GPA

You will also include the following methods.

1. The default constructor

2. A set method that gets the input from the user (please see example)

3. a print method that prints the information to the console in a “User friendly manner”.

4. Provide an overloaded set method

5. Exercise Review

Key Words

|String |concatenation |identifier |Overloaded Constructor |

|Logic Errors |Run Time Errors |Comments |Application Class |

|Worker Class |instance variables |private |public |

|return |input |output |System Console |

Review Questions

1. What is the difference between a Logical Error or a Run-time error?

2. Explain the difference between private and public in a class?

3. Input provided by JOptionPane.showInputDialog() returns what data type to the calling method?

4. Is main a method?

5. import is used for what in Java?

6. What is the Application class in Java?

7. Explain what the Worker class is in Java?

8. Explain what method overloading is in Java?

Review Exercise

1. Write a program that has a bicycle class.

a. Have the class store information that pertains to a bicycle

b. Have a method that will allow a user to enter the information about the bicycle

c. Print the information out to the user

d. The class should have at least four attributes

e. Should use three instances of the class

2. Write a program that will display the string that the user inputs All in Upper case.

3. Write a program that will output to the user the lower case version of the letter entered by the user. (Assume that all input to the program is in upper case and a letter).

Appendix A

//Modified Message class from exercise one

//By: Prof. Re

//

//CMP210

//

//Description: this class shows how to do string concatenation and use input. The student

//should use this as an example and try to create a similar program on their own.

//Copyright 2004

//License: This code is to be used for educational purposes only. No duplication or use //of this document or source code shall be used with out the expresses permission of the

//document’s author.

import javax.swing.*;

public class Message

{

private String theMesage;

public Message()

{

theMessage = “”;

}

public void setMessage()

{

theMessage = JOptionPane.showInputDialog(“Please Enter a” +

“ Message to Print”);

}

public void setMessage(String OtherMessage)

{

theMessage = OtherMessage;

}

public String toString()

{

return theMessage;

}

public void printMessage()

{

System.out.println(theMessage);

}

}

Works Cited

[1] At this point you should be familiar with All of the operators that are used in Java from the supplemental reading in the text.

[2] Except boolean

[3] Here chaAt(2) will return the letter at the 2nd indexed position in the String. In this case it is the letter o.

[4] This is due to the Math class being a static class and will be explained in more detail later in the course.

[5] Please examine ALL of the methods defined in the Math class in your text in Section 2.8 of your text

[6] Which is why it tool until Exercise 3 to tell the student how to do input.

[7] This is an important point to remember about input and how ALL input is a String.

[8] System console is the window with the black background the student has been seeing in every exercise.

[9] In order to use the swing library you must import it in every file or class that you wish to use input with.

[10] Please exam the example in the Appendix on page 11

[i] Savitch, Walter, Java An Introduction to Computer Science and Programming, Prentice Hall, New Jersey 2001, page 79

[ii] Koffman, Elliot B., Wolz, Ursula, Problem Solving with Java, Addison Wesley, New York 2002, Page 66.

-----------------------

String Name;

Name = “Bob O’reily” ;

String Message;

Mesage = “Bob O’reily”;

Message = Message + “ is here”;

String Phrase = “Hello World”;

Message MyMessage = new Message();

MyMessage.setMessage(); //calls first method

MyMessage.setMessage(Phrase);//calls second method

String U_Input;

int height;

U_Input = JOptionPane.showInputDialog(“Please enter your height”);

height = Integer.parseInt(U_Input);

String U_Input;

U_Input = JOprionPane.showInputDialog(“Please enter a word”);

This is an example how String concatenation can be used to continue a String on the next line of code.

The String entered by the user is placed into the String theMessage

int Answer;

Answer = Math.sqrt(9);

String Colour;

char letter;

Colour = “Brown”;

letter = Colour.charAt(2);

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download