using classes bcis 3680 enterprise programming. overview 2 using classes using premade classes for...

Post on 12-Jan-2016

218 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Using Classes

BCIS 3680 Enterprise Programming

2

Overview Using Classes

Using premade classes for input and output Display output: System, JOptionPane classes Format output: Decimal Format, NumberFormat classes Handling Input: Wrapper classes, e.g., Integer, Double Processing: Math class

3

Organization of Classes Related classes are organized into packages.

Java SE comes with a number of commonly used packages. To use Class A in Class B, you need to have an import statement

for Class A at the beginning of Class B. The only exception is the classes in the java.lang package, which can

be used by all other classes without an import java.lang; statement.

Two ways to write the import statement: Specifically import the name of the particular class you want to use, e.g., import java.util.Scanner;.

Import the entire package the class belongs to, e.g., import java.util.*;. All other classes in that package are accessible now.

4

Packages of “Premade” Classes Classes are grouped in packages according to functionality by using the package keyword.

The following packages ship with the Java language:Package Categories of Classes

java.lang Basic functionality common to many programs, such as the String class and Math class

java.awt Graphics classes for drawing and using colors

javax.swing User-interface components

java.text Classes for formatting numeric output

java.util The Scanner class, the Random class and other miscellaneous classes

java.io Classes for reading from and writing to files

5

The System Class

The System class is in the java.lang package, so it does not need to be imported.

Two useful static constants (variables with constant value) of the System class: in represents the standard input device (the keyboard by default). out represents the standard output device (the Java console by default).

Examples: Scanner scan = new Scanner(System.in);

System.out.println("Hello");

Using System.out

Example: System.out.print("The answer is "); System.out.println(3); The output is: The answer is 3

Return type Signaturevoid print( anyDataType argument )

prints argument to the standard output device

void println( anyDataType argument )prints argument to the standard output device followed by a newline character

7

Using Dialog Boxes The JOptionPane class is in the javax.swing

package. You must import it.

Static methods are provided for input and output dialog boxes. For input dialog boxes, return value is a String, so numeric input

needs to be converted (using methods such as parseInt() or parseDouble()).

8

JOptionPane static Methods

Return value Signature

String showInputDialog( Component parent, Object prompt, String title, int messageType )pops up an input dialog box, where prompt asks the user for input.

void showMessageDialog( Component parent, Object message, String title, int messsageType )pops up an output dialog box with message displayed.

9

Message Dialog Box Displays a message and then waits until the user press OK: showMessageDialog(Component parent, Object message, String title, int messageType) parent – use null for projects mesage – the message you want to display. A string is fine as it is an object. title – the text you want to appear on the title bar. messageType – indicates the nature of the message box. It is of the int type

but you don’t have to enter an integer. Instead, you may enter one of the following easy-to-read words and Java will translate it into an integer for you. JOptionPane.INFORMATION_MESSAGE: Standard info icon is used. JOptionPane.PLAIN_MESSAGE: No icon is displayed. JOptionPane.QUESTION_MESSAGE: Question mark icon is displayed. JOptionPane.WARNING_MESSAGE: Warning icon is displayed.

10

Input Dialog box Displays a displays a text field into which the user can enter a string. showInputDialog(Component parent, Object prompt, String title, int messsageType) parent – use null for projects prompt – the prompt you want to display. A string is fine as it’s an object. title – the text you want to appear on the title bar. messageType – indicates the nature of the message box. The options are:

JOptionPane.ERROR_MESSAGE JOptionPane.INFORMATION_MESSAGE JOptionPane.PLAIN_MESSAGE JOptionPane.QUESTION_MESSAGE JOptionPane.WARNING_MESSAGE

11

Formatting Numeric Output The DecimalFormat and NumberFormat classes allow you to

specify the display format of numbers - number of digits, number of places after the decimal, formatting elements such as dollar signs and percent signs, etc.

Both classes are in the java.text package. Importing is needed.

Usage pattern: Create a formatting object (either a DecimalFormat or a NumberFormat

object). Call the format method of the formatting object and pass the number to be

formatted as the argument. A formatting object may be used to format multiple numbers. If numbers are to be formatted in different ways, then multiple formatting objects

are needed.

12

DecimalFormat Class

Pattern characters:

0 required digit # optional digit, suppress if 0 . decimal point , comma separator % multiply by 100 and display a percent sign

DecimalFormat ConstructorDecimalFormat( String pattern )instantiates a DecimalFormat object with the format specified by pattern

13

The format( )Method

Return type SignatureString format( double number )

returns a formatted String representation of number

14

The Wrapper Classes There are occasions when you want to work with a number as

an object. Numbers are primitive types. They are not objects. Wrapper classes resolve the problem because they are objects so can

be handled as such. In the “core” of each wrapper object is a numeric value.

15

Wrapper Classes Remember the naming convention:

Primitive types start with a lowercase letter; Class names start with an uppercase letter.

Primitive Data Type Wrapper Class

double Double

float Float

long Long

int Integer

short Short

byte Byte

char Character

boolean Boolean

16

Using Wrapper Classes A handy use of wrapper class is a static method for converting

textual input into numbers. Usually, when a program obtains input from users, the input is read

as strings. Even when the user enters a number, it’s still a string (of characters that stand for numbers).

Despite looking numeric ostensibly, such strings cannot be used in mathematic operations. They must be converted into primitive types first.

To perform the conversion, call the respective parseX() method of the wrapper class. To convert a string into an integer, call parseInt(). To convert a string into a double, call parseDouble().

17

Integer Static Methods

Return value Signatureint parseInt( String s )

returns the String s as an int

Integer valueOf( String s )returns the String s as an Integer object

18

Double Static Methods

Return value Signaturedouble parseDouble( String s )

returns the String s as a double

Double valueOf( String s )returns the String s as a Double object

19

Reading Numeric Input The showInputDialog() method returns a string. To convert the string to a numeric type, use the wrapper

class methods. Example:

String input =

JOptionPane.showInputDialog(null,"Please enter your age in years.", "Get Input", JOptionPane.QUESTION_MESSAGE);

int age = Integer.parseInt(input);

20

Math Class The Math class provides static constants and static methods

for performing common calculations. The Math class is in the java.lang package, so it does not

need to be imported. Methods in the Math class are static.

21

Methods of the Math Class

Return type SignaturedataTypeOfArg abs( dataType arg )

returns the absolute value of the argument arg, which can be a double, float, int or long.

double log( double a ) returns the natural logarithm (in base e) of its argument.

double sqrt( double a ) returns the positive square root of a

double pow( double base, double exp ) returns the value of base raised to the power exp

22

The round() Method

Rounding rules: Any factional part < .5 is rounded down Any fractional part .5 and above is rounded up

Return type Signaturelong round( double a )

returns the closest integer to its argument a

23

The min() and max()Methods

Find smallest of three numbers: int smaller = Math.min( num1, num2 ); int smallest = Math.min( smaller, num3 );

Return type SignaturedataTypeOfArgs min( dataType a, dataType b )

returns the smaller of the two arguments. The arguments can be doubles, floats, ints, or longs.

dataTypeOfArgs max( dataType a, dataType b )returns the larger of the two arguments. The arguments can be doubles, floats, ints, or longs.

top related