Using Classes and Objects

Similar documents
Using Classes and Objects

Data Representation Classes, and the Java API

Using Classes and Objects

Using Classes and Objects. Chapter

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

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

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

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

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

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

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

Formatting Output & Enumerated Types & Wrapper Classes

Packages & Random and Math Classes

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

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!

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

Selection Statements and operators

Introduction to Arrays

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

Selection Statements and operators

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

Basics of Java Programming variables, assignment, and input

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

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

CSC 1051 Data Structures and Algorithms I

ECE 122. Engineering Problem Solving with Java

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

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

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

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

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

Chapter 4 Classes in the Java Class Libraries

2: Basics of Java Programming

Designing Classes part 2

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

Object-Based Programming. Programming with Objects

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

Selection and Repetition Revisited

Selection and Repetition

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

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

Methods (Deitel chapter 6)

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

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

Methods (Deitel chapter 6)

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

CSC 1051 Data Structures and Algorithms I

Data Representation and Applets

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

Java Basic Introduction, Classes and Objects SEEM

Selection and Repetition

CSC 1051 Data Structures and Algorithms I

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

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

Selection and Repetition Revisited

Applets and the Graphics class

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

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

Java Basic Introduction, Classes and Objects SEEM

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

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

Data Representation and Applets

Classes and Objects Part 1

Computational Expression

Lecture 3: Variables and assignment

Java I/O and Control Structures Algorithms in everyday life

Introduction to Computer Science I

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 26, Name: Key

Data Representation and Applets

The Math Class. Using various math class methods. Formatting the values.

Algorithms and Conditionals

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

Java I/O and Control Structures

CT 229 Java Syntax Continued

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Problem Grade Total

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

Chapter 3 Using Classes and Objects

I. Variables and Data Type week 3

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

COMP6700/2140 Std. Lib., I/O


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

Chapter 3: Using Classes and Objects

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

CMPT 125: Lecture 4 Conditionals and Loops

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

Methods CSC 121 Fall 2016 Howard Rosenthal

Lab5. Wooseok Kim

CompSci 125 Lecture 05. Programming Style, String Class and Literals, Static Methods, Packages

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:

Conditional Statements

Data Conversion & Scanner Class

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Transcription:

Using Classes and Objects 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/

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

Packages For purposes of accessing them, classes in the Java API are organized into packages Package Purpose imported automatically, includes String and Math classes 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

The Math Class The Math class contains methods that perform various mathematical functions These include: absolute value square root exponentiation trigonometric functions value = Math.cos(90) + Math.sqrt(delta);

The Math Class The Math class is part of the java.lang package No need to import anything! The Math class methods are static Static methods are invoked through the class name value = Math.cos(phi) + Math.sqrt(delta); See Quadratic.java

Some methods from the Math class this slide excerpted from http://www.cs.princeton.edu/courses/archive/fall13/cos126/lectures/02-basics.pdf

The Random Class 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]

What is a random number? 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

Example: Get some snow into the Snowman Applet! 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)?

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 See RandomNumbers.java

How about a random color? random values for R G B Color mystery = new Color(,, );

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) trial++; count++; // snake eyes System.out.println ("Probablility of snake eyes = " + (double)count/100000);

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 (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

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

The Strings Class Strings are objects defined by the String class "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

Invoking String Methods 0 1 2 3 4 name B e t s y String name = "Betsy"; As with other kinds of objects, we use the dot operator to invoke an String s methods: int numofcharsinname = name.length(); numofcharsinname length() is one of the methods of String objects (defined in the String class)

More String Methods List of some String methods: see textbook, page 119 name String name = "Betsy"; char initial = name.charat(0); 0 1 2 3 4 B e t s y initial String newname = name.replace('s', 't'); String capsname = name.toupper(); int comp = name.compareto(newname); newname capsname 0 1 2 3 4 0 1 2 3 4 See also textbook example StringMutation.java a.compareto(b) Compare strings, alphabetically: a>b è positive a=b è zero comp a<b è negative

Example: Palindrome tester Problem: 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? str 0 1 2 3 4 R A D A R

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

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); The new operator calls the Scanner constructor, which is a special method that sets up the object Variable refers to a Scanner object Constructing a new object is called instantiation an instance of the Scanner class

Creating Objects Another example: String title = new String ("Java Software Solutions"); The new operator calls the String constructor, which is a special method that sets up the object Variable refers to a String object Constructing a new object is called instantiation an instance of the String class

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 String title = new String ("Java Software Solutions"); String title = "Java Software Solutions"; This is special syntax that works only for strings