Chapter 4 Classes in the Java Class Libraries

Similar documents
Object-Based Programming. Programming with Objects

Java Classes: Random, Character A C S L E C T U R E 6

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.

ing execution. That way, new results can be computed each time the Class The Scanner

COMP 110 Programming Exercise: Simulation of the Game of Craps

Java Classes: Math, Integer A C S L E C T U R E 8

CS 302: Introduction to Programming

Reading Input from Text File

Chapter 2: Data and Expressions

Full file at

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG

Text User Interfaces. Keyboard IO plus

Chapter 2: Data and Expressions

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

Peer Instruction 1. Elementary Programming

HUDSONVILLE HIGH SCHOOL COURSE FRAMEWORK

H212 Introduction to Software Systems Honors

The Math Class (Outsource: Math Class Supplement) Random Numbers. Lab 06 Math Class

Lecture Set 2: Starting Java

static int min(int a, int b) Returns the smaller of two int values. static double pow(double a,

Lecture Set 2: Starting Java

Programming with Java

Fundamentals of Programming Data Types & Methods

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. File Input and Output

AP Computer Science Unit 1. Writing Programs Using BlueJ

A token is a sequence of characters not including any whitespace.

12/22/11. } Rolling a Six-Sided Die. } Fig 6.7: Rolling a Six-Sided Die 6,000,000 Times

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

AP Computer Science Unit 1. Writing Programs Using BlueJ

Computer Science 145 Midterm 1 Fall 2016

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

CS 211: Existing Classes in the Java Library

Chapter 4 Introduction to Control Statements

First Java Program - Output to the Screen

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

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

COMP 110/L Lecture 4. Kyle Dewey

COMP 202 Java in one week

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI

Methods CSC 121 Fall 2016 Howard Rosenthal

Methods CSC 121 Spring 2017 Howard Rosenthal

CSCI 136 Data Structures & Advanced Programming. Fall 2018 Instructors Bill Lenhart & Bill Jannen

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

Using Classes and Objects

Introduction to Computer Science Unit 2. Notes

Using Java Classes Fall 2018 Margaret Reid-Miller

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

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

Chapter 4: Conditionals and Recursion

Using Classes and Objects

C Functions. 5.2 Program Modules in C

Computational Expression

AP Computer Science Unit 1. Programs

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

CSCI 1103: File I/O, Scanner, PrintWriter

COMP 202. Java in one week

CISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software.

2.8. Decision Making: Equality and Relational Operators

Introduction to Java Unit 1. Using BlueJ to Write Programs

Experiment No: Group B_4

Object Oriented Programming. Java-Lecture 6 - Arrays

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

Topic 11 Scanner object, conditional execution

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

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

Formatting Output & Enumerated Types & Wrapper Classes

ECE 122 Engineering Problem Solving with Java


Programming for Engineers Functions

I. Variables and Data Type week 3

Introduction to Programming Using Java (98-388)

Introduction to Java Applications

Introduction to Computer Science Unit 2. Notes

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

CS110: PROGRAMMING LANGUAGE I

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

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

Basic Computation. Chapter 2

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

Object Oriented Programming. Java-Lecture 1

Data Conversion & Scanner Class

COMP200 INPUT/OUTPUT. OOP using Java, based on slides by Shayan Javed

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

Section 2.2 Your First Program in Java: Printing a Line of Text

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

4. Java Project Design, Input Methods

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

STUDENT LESSON A7 Simple I/O

BASIC INPUT/OUTPUT. Fundamentals of Computer Science

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Faculty of Science COMP-202A - Foundations of Computing (Fall 2012) - All Sections Midterm Examination

Welcome to the Using Objects lab!

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

What did we talk about last time? Examples switch statements

Mat 2170 Week 9. Spring Mat 2170 Week 9. Objects and Classes. Week 9. Review. Random. Overloading. Craps. Clients. Packages. Randomness.

BLOCK STRUCTURE. class block main method block do-while statement block if statement block. if statement block. Block Structure Page 1

Introduction to Computer Science Unit 2. Exercises

Numerical Data. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

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

AP Computer Science Java Mr. Clausen Program 6A, 6B

Transcription:

Programming Fundamental I ACS-1903 Chapter 4 Classes in the Java Class Libraries 1

Random Random The Random class provides a capability to generate pseudorandom values pseudorandom because the stream of values we can get are generated algorithmically if the initial value used and the algorithm are known, we can predict the sequence of random values For more details you can consult the book The Art of Computer Programming Volume 2 But in practice we just consider this pseudorandom is close enough to true random 2

Random Methods for random values The Random class provides methods to generate random values in boolean, integer, and double types The Math class also has a method random() that can be used to generate random double values between 0.0 (inclusive) and 1.0 3

Random To use these methods to generate random values, a program must instantiate an object from the Random class Just like what we do in creating a new scanner object before we can take any user s input There are two constructors for this purpose one that takes an argument (a seed or initial value) The advantage to using a seed is that the stream of values is always the same this can assist in debugging code. one that does not take a seed (the no-arg constructor) it actually bases its seed on the system time One cannot predict the values to be obtained from this measure Also do not forget to use the import statement to refer to java.util.random in your program 4

Random Examples Simulate rolling a six-sided dice Random has a method nextint(... ) that returns an int value between 0 and the argument provided Note the value represented by the argument is excluded! If g is a Random object, then to obtain random values as if one is rolling a sixsided die one uses: g.nextint(6)+1 Program: RollDice 5

Random Simulate tossing a coin There could be a number of approaches to do this nextint(2) generates 0 and 1 nextrandom() generates true and false nextint() generates integers - approximately half are negative and the other half are positive (or half are even and half are odd) Program: TossCoin 6

Character Character The Character class has many static methods that can be used Because the methods are static the programmer does not instantiate an object But these class methods must be prefixed with Character. Like: Character.toLowerCase(ch) 7

Character Some commonly used static methods of the Character class 8

Character Examples Detecting the type of character Still, we use the charat() of String class to access the individual characters in a string one-by-one Then determine the type of each character using isdigit() and isletter() Program: CharacterTypes Getting the numerical value of a numeric character The Character method getnumericvalue() can be used to obtain the decimal value of a character Program: SumNumericValues 9

Character Validating input In many situations a user's input must be validated before the input can be processed Without validation, a program could be crashed if the user s input is of improper type Program: ValidateStudentNumber Using the internal representations of characters Instead of using Character method getnumericvalue() we can use characters in arithmetic expressions directly Program: Exercise 5 (modified SumNumericValues) 10

Scanner We touched this before It is used to obtain data from the user via the standard input device keyboard The input from the user is a sequence of tokens Tokens are strings separated by delimiters Delimiters by default are whitespace Whitespace includes spaces tabs new line and a few other characters A programmer can define the delimiters of a token Consider that a program could be reading a file where tokens are separated by commas In this course we will stick with the defaults 11

Scanner The purpose of a Scanner object is said to parse the input stream making tokens available The use of Scanner objects we cover three usages for the Scanner class: As discussed earlier for handling input from standard input: System.in Obtaining tokens from a string Obtaining tokens from a file To use the methods in the Scanner class you must include java.util.scanner in the import statement instantiate a Scanner -- for above three usages Scanner s = new Scanner("System.in"); Scanner s = new Scanner(s); //s is of type String Scanner s = new Scanner(f); //f is of type File 12

Scanner Use Scanner on a text file In order to read a text file we must declare a Scanner object associated with that file Let us consider only files that are in our BlueJ project -- like the readme.txt Why: when the file is contained in BlueJ s project we only need to use its name as a string Scanner f = new Scanner(new File("Readme.txt")); Methods for Scanner Use with caution as a mismatch type error could cause the program to crash Like use nextint() to get a character 13

Scanner 14

Scanner Examples Reading Readme.txt DisplayReadme while (f. hasnext ()) to avoid exception error Use java.io.filenotfoundexception to for exception handling in case there is no Readme.txt in this project Scanning a string ScanString while (s. hasnext ()) again! 15

Math It contains fields for pi and e and methods for performing basic numeric operations These methods include exponential logarithm square root trigonometric other functions They are all static methods So no need to instantiate an instance first but again you must use the method name together with the prefix Math 16

Math Some of the methods we may use Refer to the table on page 135 Example FindMax Exercise 14 17

Integer It has many static fields and methods that can be used on integer These methods are static No need to instantiate an object When used must be prefixed with Integer Example TotalQuantity 18

Integer Some methods 19