using classes and objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · the math class...

29
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ CSC 1051 M.A. Papalaskari, Villanova University Using Classes and Objects

Upload: others

Post on 01-Aug-2020

19 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

CSC 1051 – Data Structures and Algorithms I

Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Course website: www.csc.villanova.edu/~map/1051/

CSC 1051 M.A. Papalaskari, Villanova University

Using Classes and Objects

Page 2: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

The Java class library or Java API (Application Programming Interface)

CSC 1051 M.A. Papalaskari, Villanova University

Page 3: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

Packages •  For purposes of accessing them, classes in the

Java API are organized into packages

Package

java.lang java.applet java.awt javax.swing java.net java.util javax.xml.parsers

Purpose

General support Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities Network communication Utilities XML document processing

CSC 1051 M.A. Papalaskari, Villanova University

imported automatically, includes String and Math classes

Page 4: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

The import Declaration •  Without importing a class, you could use its fully

qualified name

java.util.Scanner

•  Or you can import the class, and then use just the class name

import java.util.Scanner;

•  Or import all classes in a particular package (use the * wildcard character)

import java.util.*; CSC 1051 M.A. Papalaskari, Villanova University

Page 5: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

The Random Class

•  Part of the java.util package, so we import it as follows:

import java.util.Random;

CSC 1051 M.A. Papalaskari, Villanova University

Page 6: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

What is a random number?

CSC 1051 M.A. Papalaskari, Villanova University

“Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin.”

- John Von Neumann

“God does not play dice.” - Albert Einstein

The Random class provides methods that generate pseudorandom numbers

Page 7: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

Example: Using Random methods Random gen = new Random(); int a = gen.nextInt(4);

// integer in range [0,1,2,3] float b = gen.nextFloat();

//float in range [0,1),eg: 0.4589 int c = gen.nextInt(4) + 1;

//int in range [1,2,3,4]

int d = gen.nextInt(); // int in range[-2147483648 … 2147483647]

List of some Random methods: page 126

CSC 1051 M.A. Papalaskari, Villanova University

See RandomNumbers.java

Page 8: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

Quick Check

CSC 1051 M.A. Papalaskari, Villanova University

Given a Random object named gen, what range of values are produced by the following expressions? gen.nextInt(25)

gen.nextInt(6) + 1

gen.nextInt(50) + 100

gen.nextInt(10) – 5

(int)(gen.nextFloat()*10 + 1)

(int)(Math.random()*10 + 1)

0 to 24

1 to 6

100 to 149

-5 to 4

1 to 10

1 to 10

alternative way to generate pseudorandom number in the range 0…1

Page 9: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

Quick Check

CSC 1051 M.A. Papalaskari, Villanova University

Given a Random object named gen, write an expression that produces a random integer in the following ranges:

gen.nextInt(13)

gen.nextInt(20) + 1

gen.nextInt(6) + 15

gen.nextInt(11) – 10

Range 0 to 12

1 to 20

15 to 20

-10 to 0

Page 10: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

Example: counting “snake eyes” // Roll two dice 100,000 times and count how many // times you roll snake eyes, i.e., two 1’s. Random gen = new Random(); int trial = 0, count = 0; while (trial < 100000) { int die1 = gen.nextInt(6) + 1; int die2 = gen.nextInt(6) + 1;

if (die1 == 1 && die2 == 1) count++; // snake eyes trial++;

} System.out.println ("Probablility of snake eyes = " +

(double)count/100000);

CSC 1051 M.A. Papalaskari, Villanova University

Page 11: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

Try this: •  Get some snow into the Snowman Applet!

CSC 1051 M.A. Papalaskari, Villanova University

int flake = 1; while (flake <= 1000) { int x = gen.nextInt(300); int y = gen.nextInt(225);

page.fillOval(x, y, 2, 2); flake++;

}

* can you get the snowflakes to also vary in size (say, 2-4 pixels)?

Page 12: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

How about a random color?

Color mystery = new Color(__, __, __);

CSC 1051 M.A. Papalaskari, Villanova University

random values for R G B

Page 13: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

The Math Class •  The Math class contains methods that perform

various mathematical functions

•  These include: –  absolute value –  square root –  exponentiation –  trigonometric functions

CSC 1051 M.A. Papalaskari, Villanova University

value = Math.cos(90) + Math.sqrt(delta);

Page 14: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

The Math Class •  The Math class is part of the java.lang package

–  No need to import anything!

–  The Math class is special! – methods are static (also called class methods); Static methods are invoked through the class name (i.e., you do NOT need to create a Math object in order to use them)

CSC 1051 M.A. Papalaskari, Villanova University See Quadratic.java

value = Math.cos(phi) + Math.sqrt(delta);

Page 15: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

Some methods from the Math class

CSC 1051 M.A. Papalaskari, Villanova University this slide excerpted from http://www.cs.princeton.edu/courses/archive/fall13/cos126/lectures/02-Basics.pdf

Page 16: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

Strings are Objects "This is a string literal." "123 Main Street" "X"

•  defined by the String class

•  System.out is also an object - it represents a destination (the monitor screen) to which we can send output

CSC 1051 M.A. Papalaskari, Villanova University

Page 17: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

Methods •  Objects can have methods associated with them

•  In Lincoln.java we invoked the println method

System.out.println ("Whatever you are, be a good one.");

object method name information provided to the method

(parameters)

CSC 1051 M.A. Papalaskari, Villanova University

Page 18: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

Invoking Methods •  We use the dot operator to invoke an object’s methods

CSC 1051 M.A. Papalaskari, Villanova University

int numOfCharsInName = name.length();

length() is one of the methods of String objects (defined in String class)

String name = scan.nextLine(); nextLine() is one of the methods of Scanner objects (defined in Scanner class)

B y s t e

0 1 2 3 4

Page 19: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

More String Methods

int numOfCharsInName = name.length();

char initial = name.charAt(0);

B y s t e

0 1 2 3 4

String newName = name.replace('s', 't');

String capsName = name.toUpper();

String nickName = name.substring(1, 4);

0 1 2 3 4

name

newName

0 1 2 3 4

capsName

0 1 2 3 4

nickName

Page 20: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

Example: Using String methods String a = "stuff "; String b = a.concat ("more stuff"); String c = a.toUpperCase(); String d = b.replace ('r', 'v'); List of some String methods: see textbook, page 119

CSC 1051 M.A. Papalaskari, Villanova University

Page 21: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

Example: Using String methods String a = "stuff "; String b = a.concat ("more stuff"); String c = a.toUpperCase(); String d = b.replace ('r', 'v');

String e = b.substring (2, 7); char letter = c.charAt(3); int num = a.length(); int comp = a.compareTo(b); [a >> b? (use lexicographic order: positive if a>>b, zero if equal, negative if a<<b)]

List of some String methods: textbook page 119

CSC 1051 M.A. Papalaskari, Villanova University

See also textbook example StringMutation.java

Page 22: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

Palindrome tester •  Input a string, determine whether it is a palindrome,

i.e.: –  first char is the same as last char –  2nd char is the same as 2nd last char –  and so on…

•  How to express this as an algorithm? •  How to implement it?

CSC 1051 M.A. Papalaskari, Villanova University

R R A D A

0 1 2 3 4

str

Page 23: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

Copyright © 2012 Pearson Education, Inc.

System.out.println ("Enter a potential palindrome:"); str = scan.nextLine(); left = 0; right = str.length() - 1; while (str.charAt(left) == str.charAt(right) && left < right) { left++; right--; } if (left < right) System.out.println ("NOT a palindrome"); else System.out.println ("palindrome");

PalindromeTester.java (Example from Chapter 5)

Page 24: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

Copyright © 2012 Pearson Education, Inc.

System.out.println ("Enter a potential palindrome:"); str = scan.nextLine(); left = 0; right = str.length() - 1; while (str.charAt(left) == str.charAt(right) && left < right) { left++; right--; } if (left < right) System.out.println ("NOT a palindrome"); else System.out.println ("palindrome");

PalindromeTester.java (Example from Chapter 5)

Sample Run Enter a potential palindrome: radar palindrome Test another palindrome (y/n)? y Enter a potential palindrome: able was I ere I saw elba palindrome. Test another palindrome (y/n)? y Enter a potential palindrome: abracadabra NOT a palindrome. Test another palindrome (y/n)? n

Page 25: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

Declaring Variables, revisited •  Examples of variable declarations:

int count = 0;

double mpg;

String title;

Graphics page;

Color aquamarine;

Scanner scan;

•  A class name can be used as a type to declare an object reference variable

•  The object itself must be created separately CSC 1051 M.A. Papalaskari, Villanova University

Page 26: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

Creating Objects •  We have already seen something like this:

Scanner scan = new Scanner (System.in);

This calls the Scanner constructor, which is a special method that sets up the object

CSC 1051 M.A. Papalaskari, Villanova University

Variable refers to a Scanner object

Page 27: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

Creating Objects •  We have already seen something like this:

Scanner scan = new Scanner (System.in);

The new operator calls the Scanner constructor, which is a special method that sets up the object

CSC 1051 M.A. Papalaskari, Villanova University

Variable refers to a Scanner object Constructing a new object is called instantiation

an instance of the Scanner class

Page 28: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

Creating Objects •  We have already seen something like this:

The new operator calls the String constructor, which is a special method that sets up the object

CSC 1051 M.A. Papalaskari, Villanova University

Variable refers to a String object Constructing a new object is called instantiation

an instance of the String class

String title = new String ("Java Software Solutions");

Page 29: Using Classes and Objects - csc.villanova.edumap/1051/f13/03classesandobjects.pdf · The Math Class • The Math class is part of the java.lang package – No need to import anything!

The String Class is SPECIAL! •  Exception to the use of new operator: Because

strings are so common, we don't have to use the new operator to create a String object

•  This is special syntax that works only for strings

CSC 1051 M.A. Papalaskari, Villanova University

String title = new String ("Java Software Solutions");

String title = "Java Software Solutions";