CSC 222: Object-Oriented Programming. Spring 2017

Similar documents
CSC 222: Object-Oriented Programming. Spring 2013

CSC 221: Computer Programming I. Fall 2004

More on variables and methods

Strings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

CSC 221: Computer Programming I. Fall 2001

Full file at

CSC 222: Object-Oriented Programming. Fall 2015

STUDENT LESSON A10 The String Class

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

CSC 222: Object-Oriented Programming. Fall 2017

Using Java Classes Fall 2018 Margaret Reid-Miller

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4


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

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

COMP 110 Programming Exercise: Simulation of the Game of Craps

Object-oriented programming. CSC 222: Computer Programming II. Spring Java classes. Simple example: Die class. public static void main

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Chapter Goals. Contents LOOPS

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2018 Instructors: Bill & Bill

Mr. Monroe s Guide to Mastering Java Syntax

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

TeenCoder : Java Programming (ISBN )

Activity 9: Object-Oriented

AP Programming - Chapter 6 Lecture

Datatypes, Variables, and Operations

CS1004: Intro to CS in Java, Spring 2005

Defining Classes. Chap 1 introduced many concepts informally, in this chapter we will be more formal in defining

Strings. Strings and their methods. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

Math Modeling in Java: An S-I Compartment Model

Conditionals, Loops, and Style

AP Computer Science. Strings. Credit: Slides are modified with permission from Barry Wittman at Elizabethtown College

More non-primitive types Lesson 06

"Hello" " This " + "is String " + "concatenation"

9 Working with the Java Class Library

CSC 222: Object-Oriented Programming. Fall Object-oriented design

The Irving K. Barber School of Arts and Sciences COSC 111 Final Exam Winter Term II Instructor: Dr. Bowen Hui. Tuesday, April 19, 2016

CS 106A, Lecture 9 Problem-Solving with Strings

CSC 222: Object-Oriented Programming. Fall 2017

appreciate the difference between a char and a string understand and use the String class methods

Chapter 29: String and Object References Bradley Kjell (Revised 06/15/2008)

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2017 Instructors: Bill & Bill

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Computer Science 145 Midterm 1 Fall 2016

Midterms Save the Dates!

Introduction to Software Development (ISD) Week 3

Java s String Class. in simplest form, just quoted text. used as parameters to. "This is a string" "So is this" "hi"

CS 106 Introduction to Computer Science I

Lecture 8: The String Class and Boolean Zen

Designing data types. Overview. Object Oriented Programming. Alan Kay. Object Oriented Programming (OOP) Data encapsulation. Checking for equality

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Computer Science E-119 Fall Problem Set 3. Due before lecture on Wednesday, October 31

Intro to Strings. Lecture 7 CGS 3416 Spring February 13, Lecture 7 CGS 3416 Spring 2017 Intro to Strings February 13, / 16

Activity 9: Object-Oriented

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

Designing data types. Fundamentals of Computer Science I

Strings! Today! CSE String Methods!

Java Programming. String Processing. 1 Copyright 2013, Oracle and/or its affiliates. All rights reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

CSE1710. Big Picture. Tuesday, Dec 02 is designated as a study day. No classes. Thursday, Dec 04 is last lecture.

Java characters Lecture 8

Key Differences Between Python and Java

CompSci 125 Lecture 11

Conditionals, Loops, and Style. Control flow thus far. if statement. Control flow. Common branching statement Evaluate a boolean expression

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

CS112 Lecture: Characters and Strings

Chapter 7 User-Defined Methods. Chapter Objectives

Programming with Java

APCS Semester #1 Final Exam Practice Problems

String is one of mostly used Object in Java. And this is the reason why String has unique handling in Java(String Pool). The String class represents

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

COMP 401 Midterm. Tuesday, Oct 18, pm-3:15pm. Instructions

Assignment 1 due Monday at 11:59pm

Review: Python Transi,on Warning

Midterms Save the Dates!

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Building Java Programs Chapter 2

Utilities (Part 2) Implementing static features

Java Coding 3. Over & over again!

Netbeans tutorial:

Introduction to the Java Basics: Control Flow Statements

CPS122 Lecture: Defining a Class

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Midterm Examination

CITS1001 week 6 Libraries

AP Computer Science A

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

CMPT 125: Lecture 3 Data and Expressions

2. All the strings gets collected in a special memory are for Strings called " String constant pool".

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Java Classes and Objects

Chapter 11: Create Your Own Objects

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

Computer Science 300 Sample Exam Today s Date 100 points (XX% of final grade) Instructor Name(s) (Family) Last Name: (Given) First Name:

Using Classes and Objects

Topic 3 Encapsulation - Implementing Classes

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Computer Science 252 Problem Solving with Java The College of Saint Rose Spring Topic Notes: Strings

Lecture 5. Assignments. Arithmetic Operations. Arithmetic Operations -Summary 1/24/18. Lab 3: Variables and operations. Read Sections

Transcription:

CSC 222: Object-Oriented Programming Spring 2017 Simulations & library classes HW3: RouletteWheel, RouletteGame, RouletteTester javadoc java.lang classes: String, Character, Integer java.util.random for loop static fields & methods 1 Simulations programs are often used to model real-world systems often simpler/cheaper to study a model easier to experiment, by varying parameters and observing the results dot race is a simple simulation utilized Die object to simulate random steps of each dot HW3: you will use & develop classes that simulate different betting strategies for roulette if you start with 100 credits and play 100 spins of the wheel, what is your best strategy for winning? how do we define winning? ending the rounds with a profit? ending the rounds with the most credits? 2 1

Spam alert 3 HW3 classes you will be given the RouletteWheel class that models a wheel given its specifications, you will write the RouletteGame class that uses RouletteWheel to simulate a game with betting you will be given the RouletteTester class that uses RouletteGame to perform repeated simulations and display stats finally, you will modify RouletteTester to perform Martingale betting & analyze its effectiveness recall: Die is used by lots of other classes 4 2

Abstraction & classes note that RouletteGame will depend upon RouletteWheel but you don't have to know the details of how that class works can abstract away the details and focus on its behavior recall that javadoc comments can be used to document the behavior of a class always include javadoc comments for each class (incl. @author & @version) and for every method (incl. @param & @return) 5 Java Standard Library the Java language provides an extensive library of nearly 4,000 classes documentation for the entire library is accessible in javadoc form to view in BlueJ, select Java Class Libraries under the Help menu 6 3

String class one of the most useful library classes is String technically, its full name is java.lang.string, but the java.lang prefix can be omitted a String object encapsulates a sequence of characters and many useful methods since Strings are so common, Java provides shortcuts to make them easier to use (and look like primitives) String str = "foo"; è String str = new String("foo"); we have already seen a few basic operations on Strings you can display Strings using System.out.print and System.out.println System.out.println(firstName); the '+' operator concatenates two strings (or string and number) together String str = "foo" + "lish" + 1; 7 String javadoc many of the javadoc details will be revealed later for now, important feature is that we can scan the constructors & methods of a class String has MANY of each can click on a constructor/method link to see more details 8 4

Common String methods int length() returns number of chars in String char charat(int index) returns the character at the specified index (indices range from 0 to str.length()-1) boolean contains(string str) returns true if str occurs in the String, else false int indexof(char ch) returns index where ch/str first occurs in the int indexof(string str) String (-1 if not found) String substring(int start, int end) returns the substring from indices start to (end-1) String touppercase() returns copy of String with all letters uppercase String tolowercase() returns copy of String with all letters lowercase boolean equals(string other) returns true if other String has same value int compareto(string other) returns -1 if less than other String, 0 if equal to other String, 1 if greater than other String 9 Character class recall: in Java, strings and characters are different types String is a class, char is a primitive type the (java.lang.)character class has numerous static methods for manipulating characters char tolowercase(char ch) char touppercase(char ch) boolean isletter(char ch) returns lowercase copy of ch returns uppercase copy of ch returns true if ch is a letter boolean islowercase(char ch) returns true if lowercase letter boolean isuppercase(char ch) returns true if uppercase letter 10 5

String/Character examples public boolean isvowel(char ch) { String vowels = "aeiouaeiou"; return vowels.contains(""+ch); public char randomchar(string str) { Die d = new Die(str.length()); return str.charat(d.roll()-1); public String capitalize(string str) { if (str.length() == 0) { return str; else { return Character.toUpperCase(str.charAt(0)) + str.substring(1, str.length()); 11 Comparing strings comparison operators (< <= > >=) are defined for primitives but not objects String str1 = "foo", str2 = "bar"; if (str1 < str2) // ILLEGAL == and!= are defined for objects, but don't do what you think if (str1 == str2) // TESTS WHETHER THEY ARE THE // SAME OBJECT, NOT WHETHER THEY // HAVE THE SAME VALUE! Strings are comparable using the equals and compareto methods if (str1.equals(str2)) // true IF THEY REPRESENT THE // SAME STRING VALUE if (str1.compareto(str2) < 0) // RETURNS neg # if str1 < str2 // RETURNS 0 if str1 == str2 // RETURNS pos # if str1 > str2 12 6

Comparison example suppose we wanted to compare two names to see which comes first alphabetically Kelly Jones < Kelly Miller < Chris Smith < Pat Smith public void comparenames(string myfirst, String mylast, String yourfirst, String yourlast) { int lastcompare = mylast.compareto(yourlast); int firstcompare = myfirst.compareto(yourfirst); if (lastcompare < 0 (lastcompare == 0 && firstcompare < 0)) { System.out.println("My name comes before yours alphabetically!"); else if (lastcompare > 0 (lastcompare == 0 && firstcompare > 0)) { System.out.println("Your name comes before mine alphabetically!"); else { System.out.println("We have the same name!"); note: we have been using == to compare Strings up to this point Ø dangerous sometimes it works, sometimes it doesn't! Ø from now on, always use.equals for Strings 13 RouletteWheel implementation we can use a Die object to choose between 38 values the spin method must return a String, since we may want to differentiate between 0 and 00 38 à "00", 37 à "0" 1-36 are converted to a string by concatenating with the empty string e.g., ""+36 à ""+"36" à "36" the Die field already keeps track of the number of rolls/spins public class RouletteWheel { private Die roller; public RouletteWheel() { this.roller = new Die(38); public String spin() { int number = this.roller.roll(); if (number == 38) { return "00"; else if (number == 37) { return "0"; else { return ""+number; public int getnumberofspins() { return this.roller.getnumrolls(); public String getcolor(string slotvalue) { // NEXT SLIDE public String getparity(string slotvalue) { // SLIDE AFTER THAT 14 7

RouletteWheel implementation (cont.) getting the color associated with a number is not obvious we could have a large cascading if else to map each number to a color instead can use the String method contains rednums & blacknums contain all the numbers of each color, with spaces to see if "3" is red/black, see if rednums/blacknums contains " 3 " public class RouletteWheel {... public String getcolor(string slotvalue) { String rednums = " 1 3 5 7 9 12 14 16 18 19 21 23 25 27 30 32 34 36 "; String blacknums = " 2 4 6 8 10 11 13 15 17 20 22 24 26 28 29 31 33 35 "; if (rednums.contains(" "+slotvalue+" ")) { return "red"; else if (blacknums.contains(" "+slotvalue+" ")) { return "black"; else { return "green"; 15 RouletteWheel implementation (cont.) similarly, could have a large cascading if else to map each number to odd/even or, could use charat to access the last digit, see if it is "0", "2", "4", "6", or "8" instead, the (java.lang.)integer class contains a static method for converting a string of digits into an int: parseint e.g., Integer.parseInt("14") à 14 public class RouletteWheel {... public String getparity(string slotvalue) { int numval = Integer.parseInt(slotValue); if (numval == 0) { return "zero"; else if (numval % 2 == 0) { return "even"; else { return "odd"; 16 8

Random class instead of the Die class, we could have used the java.util.random class the nextint method returns a random int from 0..(parameter-1) other methods can be used to generate different random numbers 17 RouletteWheel w/ Random classes defined within the java.lang library are automatically available java.lang.math java.lang.system java.lang.string java.lang.character java.lang.integer we won't list the unnecessary prefix (but Javadoc will) for other libraries, must explicitly import the class import java.util.random; public class RouletteWheel { private Random randgen; public RouletteWheel() { this.randgen = new Random(); public String spin() { int number = this.randgen.nextint(38); if (number == 37) { return "00"; else { return ""+number; public int getnumberofspins() { // SAME AS BEFORE public String getcolor(string slotvalue) { // SAME AS BEFORE public String getparity(string slotvalue) { // SAME AS BEFORE 18 9

Logic-driven vs. counter-driven loops sometimes, the number of repetitions is unpredictable loop depends on some logical condition, e.g., roll dice until 7 is obtained often, however, the number of repetitions is known ahead of time loop depends on a counter, e.g., roll dice 100 times, traverse every char in string int rep = 0; while (rep < numrolls) { System.out.println( d6.roll() + d6.roll() ); rep++; in general (counting up): int rep = 0; while (rep < #_OF_REPS) { CODE_TO_BE_EXECUTED rep++; int countnum = 10; while (countnum > 0) { System.out.println(countNum); countnum--; System.out.println("BLASTOFF"); in general (counting down): int rep = #_OF_REPS; while (rep > 0) { CODE_TO_BE_EXECUTED rep--; 19 For loops since counter-controlled loops are fairly common, Java provides a special notation for representing them a for loop combines all of the loop control elements in the head of the loop int rep = 0; for (int rep = 0; rep < NUM_REPS; rep++) { while (rep < NUM_REPS) { STATEMENTS_TO_EXECUTE STATEMENTS_TO_EXECUTE rep++; execution proceeds exactly as the corresponding while loop the advantage of for loops is that the control is separated from the statements to be repeatedly executed also, since all control info is listed in the head, much less likely to forget something 20 10

For loop examples: int countnum = 10; while (countnum > 0) { System.out.println(countNum); countnum--; System.out.println("BLASTOFF!"); for (int countnum = 10; countnum > 0; countnum--) { System.out.println(countNum); System.out.println("BLASTOFF!"); Die d6 = new Die(); int numrolls = 0; int count = 0; while (numrolls < 1000) { if (d6.roll() + d6.roll() == 7) { count++; numrolls++; System.out.println(count); Die d6 = new Die(); int count = 0; for (int numrolls = 0; numrolls < 1000; numrolls++) { if (d6.roll() + d6.roll() == 7) { count++; System.out.println(count); int roundnum = 0; while (roundnum < 100) { int credits = game.checkcredits(); if (credits > 0) { int betamt = Math.min(3, credits); game.makebet(betamt, "red"); roundnum++; for (int roundnum = 0; roundnum < 100; roundnum++) { int credits = game.checkcredits(); if (credits > 0) { int betamt = Math.min(3, credits); game.makebet(betamt, "red"); 21 Variable scope scope: the section of code in which a variable exists for a field, the scope is the entire class definition for a parameter, the scope is the entire method for a local variable, the scope begins with its declaration & ends at the end of the enclosing block (i.e., right curly brace) public class DiceStuff { private Die d6;... public void showsevens(int numreps) { int count = 0; for (int numrolls = 0; numrolls < numreps; numrolls++) { if (d6.roll() + d6.roll() == 7) { count++; System.out.println(count);... since each method defines its own scope, can reuse the same parameter/local variable name in multiple methods within a method, can have a parameter/local variable with same name as a field (although confusing) use this. to differentiate 22 11

Static fields & constants we saw in the Dot class how to make a field static a field declared to be static is shared by all objects of that class useful when there is data that needs to be accessed/updated by all objects (e.g., the dot number) also useful for constants values that will not change during execution (so there is no reason for object to have its own copy) public class RouletteTester { public final static int DEFAULT_START = 100; public final static int DEFAULT_BET = 1; // METHODS CAN ACCESS THESE CONSTANTS note: constants are initialized when declared (not in a constructor) convention is to use all caps for constants any attempt to reassign a final value will cause a compiler error 23 Static methods sometimes a class doesn't require fields (other than constants) without fields, every object of the class would look/behave exactly the same essentially, it is a collection of independent functions/methods so, why even create objects at all? the alternative is to declare the methods to be static ü that way, they belong to the class ü you can call them directly on the class, without creating an object public class RouletteTester { public final static int DEFAULT_START = 100; public final static int DEFAULT_BET = 1; public static int playround(string bettype, int betsperround) { public static void playstats(string bettype, int numrounds, int betsperround) { 24 12