Using Classes and Objects

Similar documents
Using Classes and Objects

Data Representation Classes, and the Java API

Using Classes and Objects

We now start exploring some key elements of the Java programming language and ways of performing I/O

Using Classes and Objects. Chapter

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 7, Name:

A variable is a name for a location in memory A variable must be declared

Objectives of CS 230. Java portability. Why ADTs? 8/18/14

Chap. 3. Creating Objects The String class Java Class Library (Packages) Math.random() Reading for this Lecture: L&L,

Packages & Random and Math Classes

Learning objectives: Objects and Primitive Data. Introduction to Objects. A Predefined Object. The print versus the println Methods

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Introduction to Arrays

CSCI 2010 Principles of Computer Science. Basic Java Programming. 08/09/2013 CSCI Basic Java 1

Selection Statements and operators

Selection Statements and operators

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

Designing Classes. Where do objects come from? Where do objects come from? Example: Account datatype. Dr. Papalaskari 1

Where do objects come from? Good question!

Basics of Java Programming variables, assignment, and input

CSC 1051 Data Structures and Algorithms I

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Java Bootcamp - Villanova University. CSC 2014 Java Bootcamp. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Class API. Class API. Constructors. CS200: Computer Science I. Module 19 More Objects

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

2: Basics of Java Programming

Data Representation and Applets

Formatting Output & Enumerated Types & Wrapper Classes

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 6, Name:

Selection and Repetition Revisited

Selection and Repetition

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Applets and the Graphics class

Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Selection and Repetition

Selection and Repetition Revisited

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 25, Name: KEY A

CSC 1051 Data Structures and Algorithms I

Data Representation and Applets

Designing Classes part 2

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Data Representation and Applets

class declaration Designing Classes part 2 Getting to know classes so far Review Next: 3/18/13 Driver classes:

Java Basic Introduction, Classes and Objects SEEM

Algorithms and Conditionals

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Java I/O and Control Structures Algorithms in everyday life

Designing Classes. Where do objects come from? Where do objects come from? Example: Account datatype. Dr. Papalaskari 1

Lecture 3: Variables and assignment

Java Libraries. Lecture 6 CGS 3416 Fall September 21, 2015

Computational Expression

Java Basic Introduction, Classes and Objects SEEM

Java I/O and Control Structures

Introduction to Computer Science I

CSC 1051 Data Structures and Algorithms I

CSC Algorithms and Data Structures I. Midterm Examination February 25, Name:

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

Preparation: Get to know the Java coordinate system. 3. How is the background color of the window specified? Copy the exact code:

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

Conditional Statements

Classes and Objects Part 1

Control flow, conditionals, boolean expressions, block statements, nested statements. Course website:

Name: Checked: Access the Java API at the link above. Why is it abbreviated to Java SE (what does the SE stand for)?

Chapter 4 Classes in the Java Class Libraries

Improved algorithm. Java code. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 9, Name: KEY

Java code. Updated program. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm. Improved algorithm

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

CSC 1051 Algorithms and Data Structures I. Final Examination May 12, Name

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

ECE 122 Engineering Problem Solving with Java

Name: Checked: Access the Java API at the link above. Why is it abbreviated to Java SE (what does the SE stand for)?

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Object-Based Programming. Programming with Objects

Chapter 3 Using Classes and Objects


Assignment 1 due Monday at 11:59pm

Supplementary Test 1

Overview. Software Code is Everywhere. Software Crisis. Software crisis Development approaches Reusability Java packages API Sample classes:

I. Variables and Data Type week 3

Data Conversion & Scanner Class

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 24, Name: KEY 1

Chapter 3: Using Classes and Objects

Full file at

Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6

Problem Grade Total

Chapter. Let's explore some other fundamental programming concepts

Introduction to Programming Using Java (98-388)

CSC 1051 Algorithms and Data Structures I. Midterm Examination March 2, Name:

Transcription:

Using Classes and Objects The Java class library or Java API (Application Programming Interface) 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/ Packages For purposes of accessing them, classes in the Java API are organized into packages The Math Class The Math class is part of the java.lang package and contains methods for mathematical functions Package Purpose imported automatically, includes String and Math classes No need to import anything! The Math class methods are static java.lang java.applet java.awt javax.swing java.net java.util javax.xml.parsers General support Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities Network communication Utilities XML document processing Static methods are invoked through the class name value = Math.cos(phi) + Math.sqrt(delta); See Quadratic.java Dr. Papalaskari 1

Some methods from the Math class Example: Global Warming // Dangerous rising sea levels in front of snowman! page.setcolor(color.blue); final int APPLET_HEIGHT = 225, APPLET_WIDTH = 300; final int WAVE_HEIGHT = 25; final double SCALE_FACTOR = 0.06; // adjust to get more/fewer waves int position = 0; while (position < APPLET_WIDTH) double wavefunction = WAVE_HEIGHT * Math.sin(position * SCALE_FACTOR); int topofwave = (int) (wavefunction + APPLET_HEIGHT / 2); page.fillrect(position, topofwave, 1, APPLET_HEIGHT - topofwave ); position++; this slide excerpted from http://www.cs.princeton.edu/courses/archive/fall13/cos126/lectures/02-basics.pdf The Random Class What is a random number? Part of the java.util package, so import it import java.util.random; Create a Random object named gen: Random gen = new Random(); Use Random method nextint()to generate a random number: int a = gen.nextint(4); // integer in range [0,1,2,3] 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 Dr. Papalaskari 2

Example: Get some snow into the Snowman Applet! int flake = 1; while (flake <= 1000) int x = gen.nextint(300); int y = gen.nextint(225); How about a random color? random values for R G B Color mystery = new Color(,, ); page.filloval(x, y, 2, 2); flake++; * can you get the snowflakes to also vary in size (say, 2-4 pixels)? Quick Check 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 0 to 24 1 to 6 100 to 149-5 to 4 1 to 10 1 to 10 Quick Check Given a Random object named gen, write an expression that produces a random integer in the following ranges: Range 0 to 12 1 to 20 15 to 20-10 to 0 gen.nextint(13) gen.nextint(20) + 1 gen.nextint(6) + 15 gen.nextint(11) 10 Dr. Papalaskari 3

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); Summary: Generating pseudorandom numbers Random gen = new Random(); int a = gen.nextint(4); // integer in range [0,1,2,3] int b = gen.nextint(4) + 1; //int in range [1,2,3,4] int c = gen.nextint(); // int in range[-2147483648 2147483647] float d = gen.nextfloat(); //float in range [0,1),eg: 0.4589 double e = Math.random(); //double in range [0,1),eg: 0.4589 int f = (int) (Math.random() * 4); Math class method // integer in range [0,1,2,3] (same as a, above) See also RandomNumbers.java The Strings Class Invoking String Methods Strings are objects defined by the String class name B e t s y "This is a string literal." "123 Main Street" "X" the String class has many methods that can be used to process text. Examples: finding the length of a string finding the char at a certain position of a string producing an all-caps version of a string String name = "Betsy"; As with other kinds of objects, we use the dot operator to invoke a String s methods: int numofcharsinname = name.length(); method in String class numofcharsinname Dr. Papalaskari 4

More String Methods String name = "Betsy"; name B e t s y char initial = name.charat(0); initial String newname = name.replace('s', 't'); newname String capsname = name.touppercase(); capsname Example: Palindrome tester Problem: Input a string, determine whether it is a palindrome, i.e.: str R A D 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? A R int comp = name.compareto(newname); comp a.compareto(b) Compare strings, alphabetically: a>b è positive a=b è zero a<b è negative See also textbook example StringMutation.java http://www.csc.villanova.edu/~map/1051/chap05/palindrometester.java (Example from Chapter 5) 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"); http://www.csc.villanova.edu/~map/1051/chap05/palindrometester.java (Example from Chapter 5) 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++; Sample Run right--; Enter a potential palindrome: radar palindrome if (left < right) System.out.println ("NOT a palindrome"); Test another palindrome (y/n)? y else Enter a potential palindrome: System.out.println ("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 CSC 1051 M.A. palindrome Papalaskari, Villanova (y/n)? University n Dr. Papalaskari 5

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 Creating Objects We have already seen something like this: Scanner scan = new Scanner (System.in); Variable refers to a Scanner object The new operator calls the Scanner constructor, which is a special method that sets up the object an instance of the Scanner class Constructing a new object is called instantiation Creating Objects Another example: String title = new String ("Java Software Solutions"); 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 The new operator calls the String constructor, which is a special method that sets up the object String title = new String ("Java Software Solutions"); Variable refers to a String object an instance of the String class Constructing a new object is called instantiation String title = "Java Software Solutions"; This is special syntax that works only for strings Dr. Papalaskari 6