Using Java Classes Fall 2018 Margaret Reid-Miller

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

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

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

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

Full file at

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

Programming with Java

Primitive Data Types: Intro

CHAPTER 4 MATHEMATICAL FUNCTIONS, CHARACTERS, STRINGS

Computational Expression

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

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

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

AP Computer Science A

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java

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

c) And last but not least, there are javadoc comments. See Weiss.

CSC 1051 Algorithms and Data Structures I. Midterm Examination March 1, Name: KEY A

Programming with Java

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

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

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

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

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

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

Chapter. Let's explore some other fundamental programming concepts

Computer Science 145 Midterm 1 Fall 2016

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

Hello World. n Variables store information. n You can think of them like boxes. n They hold values. n The value of a variable is its current contents

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

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

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Introduction to Programming Using Java (98-388)

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

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


Pace University. Fundamental Concepts of CS121 1

Midterms Save the Dates!

STUDENT LESSON A7 Simple I/O

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

Oct Decision Structures cont d

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

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Full file at

Section 2: Introduction to Java. Historical note

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

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Midterm Exam 2 Thursday, November 15th, points (15% of final grade) Instructors: Jim Williams and Marc Renault

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

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

Chapter 2: Basic Elements of Java

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

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

Important Java terminology

Classes and Objects Part 1

ICSE Class 10 Computer Applications ( Java ) 2014 Solved Question Paper

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

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

More on variables and methods

Introduction to Java (All the Basic Stuff)

2: Basics of Java Programming

Chapter 2: Data and Expressions

CS 302: Introduction to Programming

Introduction to Computer Science Unit 2. Notes

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

Chapter 4 Mathematical Functions, Characters, and Strings

CS110: PROGRAMMING LANGUAGE I

Chapter 2: Data and Expressions

Text User Interfaces. Keyboard IO plus

What did we talk about last time? Examples switch statements

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

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

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

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

Program Elements -- Introduction

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

CMPT 125: Lecture 3 Data and Expressions

Chapter 2 Part 2 Edited by JJ Shepherd, James O Reilly

More non-primitive types Lesson 06

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

Peer Instruction 1. Elementary Programming

double float char In a method: final typename variablename = expression ;

Chapter 3: Using Classes and Objects

ECE 122 Engineering Problem Solving with Java

HUDSONVILLE HIGH SCHOOL COURSE FRAMEWORK

AP Computer Science Unit 1. Programs

CS 106 Introduction to Computer Science I

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Fundamentals of Programming Data Types & Methods

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Lecture 2 Tao Wang 1

Input. Scanner keyboard = new Scanner(System.in); String name;

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

CS1150 Principles of Computer Science Math Functions, Characters and Strings (Part II)

Key Differences Between Python and Java

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

A Quick and Dirty Overview of Java and. Java Programming

Java Fall 2018 Margaret Reid-Miller

AP CS Unit 3: Control Structures Notes

Transcription:

Using Java Classes 15-121 Fall 2018 Margaret Reid-Miller

Today Strings I/O (using Scanner) Loops, Conditionals, Scope Math Class (random) Fall 2018 15-121 (Reid-Miller) 2

The Math Class The Math class contains mathematical constants and methods for common mathematical operations. Example: static double sqrt(double n) static indicates that we call this method using the name of the class. double indicates the data type of the answer the method returns. sqrt is in the Math class double answer = Math.sqrt(16.0); // returns 4.0 method header Fall 2018 15-121 (Reid-Miller) 3

The Math Class Math constants: The constants e and π are defined in the Math class. By convention, names of constants are in all upper case: Math.E and Math.PI Some Math methods: static double floor(double num) static double ceil(double num) static double sqrt(double num) static double pow(double num, double power) static int abs(int num) static double abs(double num) Method signature Example of method overloading, where abs is defined two ways. Fall 2018 15-121 (Reid-Miller) 5

Testing for Equality with doubles Which statement will Java print? double x = Math.sqrt(2.0); double y = x * x; if (y == 2.0) { System.out.println("sqrt(2) * sqrt(2) is 2"); } else { System.out.println("sqrt(2) * sqrt(2) + is not 2. It is " + y); } Never test for exact equality with floating point numbers! Fall 2018 15-121 (Reid-Miller) 8

Testing for Equality with doubles Because of round-off errors, you should test if the numbers are close. double tolerance = 1.0e-10; double x = Math.sqrt(2.0); double y = x * x; if (Math.abs(y - 2.0) < tolerance) { System.out.println("sqrt(2) * sqrt(2) is 2"); } else { System.out.println("sqrt(2) * sqrt(2) + is not 2. It is " + y); } Fall 2018 15-121 (Reid-Miller) 9

Java Data: Primitive vs Objects Primitive data: Data small fixed amount of memory. There are exactly eight primitive data types. byte, short, int, long, float, double, char, boolean Primitive data types names are in all lower case. A primitive is only data and has no other special abilities. You cannot define new primitive data types. Fall 2018 15-121 (Reid-Miller) 10

Java Data: Primitive vs Objects Objects (instance of a class): An object has both state and behaviors. An object s current state (data) is defined by the values for its attributes. These values are internally and may require a little or a lot of memory. An object s behaviors (methods) are the actions it can perform. The type (or category) of an object is its class. Java has many classes already defined, e.g., String, System, Scanner. (Recall: Class names start with a capital letter.) Fall 2018 15-121 (Reid-Miller) 11

Class as a type A class is like a blueprint from which an object is created. We can create many objects from the class. The differences among these objects are the attribute values (data) that define the objects state. For example, a class Student might be used to create a student object. All such objects would have attributes common to students (e.g., name, andrewid, courses enrolled ). But each object would have its own values for these attributes, depending on which student it represents. (Later we will see how define new classes.) Fall 2018 15-121 (Reid-Miller) 12

Object State What state (data) an object holds internally often is hidden from us, the user of the object. We cannot access the data directly. For example, a String object holds the string of characters in the object. But it might hold other hidden information relating to the string, e.g., the length of the string. Another example is the System.out object that holds information about how and to where to write text to the console. We do not need to access these data in order to use the object; we just need to call the print or println methods. Fall 2018 15-121 (Reid-Miller) 13

Object Behaviors To use an object, we need to know only the behaviors of an object. An object s behaviors are defined by a set of methods associated with the object. For example, methods may enable you to access or change an object s attribute values, or to ask the object to perform a task. These methods are known as the interface to the object. Fall 2018 15-121 (Reid-Miller) 14

String Objects An object of type String holds a sequence of (unicode) characters. When we declare a variable of type String, it does not create an object. All you get is a way to refer to the object: String founder; value is null To create an object we use the new operator: founder = new String("Carnegie"); initializes its state Strings have a shortcut way of creating them: String founder2 = "Mellon"; Fall 2018 15-121 (Reid-Miller) 15

Object vs Primitive Data A primitive variable holds an actual value: int count = 15100; count 15100 An object variable holds a reference (address) to the object (how to find the object). String founder = new String("Carnegie"); founder a35f3cd reference: computer generated address a35f3cd "Carnegie" length() substring() A String object object data object methods Fall 2018 15-121 (Reid-Miller) 16

Escape Sequences How do you include a " in a String literal? You cannot have a String literal break across lines. How do you include a line break? Solution: An escape sequence is a two-character sequence that represent a single special character. Sequence \t \n \ \ \\ Meaning tab character newline character double quote single quote backslash character Fall 2018 15-121 (Reid-Miller) 17

No static qualifier String Length int length() BEHAVIOR: Returns the number of characters in this string. Because String objects may have different lengths, you need to ask the object for its length. (It is nonstatic method.) Example: String founder = "Carnegie"; int numchar = founder.length(); object dot operator method Fall 2018 15-121 (Reid-Miller) 18

Getting a single character char charat(int index) BEHAVIOR: Returns the character at a specified index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 C a r n e g i e M e l l o n Example: String school = "Carnegie Mellon"; char firstchar = school.charat(0); WARNING: You cannot assign a char to an object of type String without first converting the char to a String object! e.g., String initial = "" + firstchar; Fall 2018 15-121 (Reid-Miller) 19

Substrings Another example of method overloading, where the number of parameters differs. String substring(int startindex, int endindex) String substring(int startindex) BEHAVIOR: Returns a new string consisting of the substring starting at startindex (inclusive) and ending at endindex (exclusive) or, if one parameter, at the last character. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 C a r n e g i e M e l l o n Example: String school = "Carnegie Mellon"; String founder = school.substring(0, 8); String founder2 = school.substring(9); Fall 2018 15-121 (Reid-Miller) 20

Replacing Characters String replace(char oldchar, char newchar) BEHAVIOR: Returns a new String object resulting from replacing every occurrence of oldchar with newchar. The original String object is unchanged. (Strings are immutable!) Example: String founder = "Carnegie"; System.out.println( founder.replace('e', 'E')); System.out.println(founder); OUTPUT: CarnEgiE Carnegie Fall 2018 15-121 (Reid-Miller) 21

Changing Case String touppercase() BEHAVIOR: Returns a new String object with all letters converted to uppercase. String tolowercase() BEHAVIOR: Returns a new String object with all letters converted to lowercase. Example: String founder = "Carnegie"; String upper = founder.touppercase(); String lower = founder.tolowercase(); Immutable: You need to print or assign the result to a variable! Fall 2018 15-121 (Reid-Miller) 22

Testing For Equality For primitive values use == for equality testing. For objects, use the equals method for testing equal contents. The argument must be the same type as the object on which equals() is called. The method returns true or false depending on whether both objects are equal or not. For example, let day be an int variable and month be a String variable. if (day == 1 && month.equals( APRIL )) { System.out.println( It s April Fool s Day ); } Two String objects are equal if they have exactly the same characters, including case and number of characters. Fall 2018 15-121 (Reid-Miller) 24

Method order The dot(.) operator is evaluated from left to right. If a method returns an object, you can invoke one of the returned object s methods. Example: String school = Carnegie Mellon"; System.out.println( school.substring(9).tolowercase() ); "Mellon" "mellon" Fall 2018 15-121 (Reid-Miller) 25

Reading User Input The Scanner class has methods for reading user input values while the program is running. The Scanner class is in the java.util package. Related classes are grouped into packages. Most of the classes we use are in the java.lang package, which is always available. To use classes in other packages we must tell the compiler about these packages by using an import declaration before the classheader: import java.util.scanner; Fall 2018 15-121 (Reid-Miller) 26

Scanner Object First, we need to create a Scanner object using the new operator: Scanner console = new Scanner(System.in); console is a variable that refers to the Scanner object. Scanner() is the constructor that helps set up the object. System.in is an object that refers to the standard input stream which, by default, is the keyboard. Fall 2018 15-121 (Reid-Miller) 27

String nextline() Scanner Methods Reads and returns the next line of input. String next() Reads and returns the next token (e.g., one word, one number). double nextdouble() Reads and returns the next token as a double value. int nextint() Reads and returns the next token as an int value. These methods pause until the user has entered some data and pressed the return key. Fall 2018 15-121 (Reid-Miller) 28

import java.util.scanner; Scanner Example Scanner console = new Scanner(System.in); System.out.print( "What is the make of your vehicle? "); String vehiclemake = console.nextline(); System.out.print( "How many miles did you drive? "); int miles = console.nextint(); System.out.print( "How many gallons of fuel did you use? "); double gallons = console.nextdouble(); Fall 2018 15-121 (Reid-Miller) 29

Scanner Caveats nextint, nextdouble, and next read one token at a time. Tokens are delimited by whitespace (space, tab, newline characters) Several values can be on the same input line or on separate lines. nextline reads the rest of the line and moves to the next line. It may return a string of no characters if it is called after calling one of the above methods. What happens if the user does not enter an integer when we use nextint? Fall 2018 15-121 (Reid-Miller) 30

Conditionals if (boolean_expression) statement if (boolean_expression) statement1 else statement2 A statement can be any Java statement: A simple statement A compound statement, such as an if statement A block statement, a group of statements enclosed in braces {} Fall 2018 15-121 (Reid-Miller) 31

The Dangling else Problem When an if statement is nested inside the then clause of another if statement, the else clause is paired with the closest if statement without an else clause. if (x > 0) else if (y > 0) color = red ; color = blue ; Misleading indentation Fall 2018 15-121 (Reid-Miller) 32

The Dangling else Problem In reality it is if (x > 0) if (y > 0) color = red ; else color = blue ; y x Fall 2018 15-121 (Reid-Miller) 33

The Dangling else Problem Use braces to pair else with the outer if if (x > 0) { if (y > 0) color = red ; } else { color = blue ; } y x Fall 2018 15-121 (Reid-Miller) 34

Multiple Alternatives Determine if a number is positive, negative, or zero: if (value < 0) { System.out.println( Value is negative. ); } else if (value == 0) { System.out.println( Value is zero. ); } else if (value > 0) { System.out.println( Value is positive. ); } At most one statement is executed. Each choice, however, is at same indentation. Fall 2018 15-121 (Reid-Miller) 35

Multiple Alternatives Determine if a number is positive, negative, or zero: if (value < 0) { System.out.println( Value is negative. ); } else if (value == 0) { System.out.println( Value is zero. ); } else { // value must be positive System.out.println( Value is positive. ); } It is clear, exactly one statement is executed. Fall 2018 15-121 (Reid-Miller) 36

Loops initialize while (test) { do_stuff update } for (initialize; test; update) { do_stuff } initialize do { do_stuff update } while (test); Note: do-statement executes loop at least once rarely used Fall 2018 15-121 (Reid-Miller) 38

Generating Random Numbers static double Math.random() returns a random double in the range [0.0,1.0). Random integer from 0 to 9? (int)(math.random() * 10); Random integer from 1 to 6? (int)(math.random() * 6) + 1; includes 0.0 excludes 1.0 () are critical! Fall 2018 15-121 (Reid-Miller) 40

Generating Random Integers Generate a random integer in {5, 15, 25,,75}: 1. How many different integers do we want to generate? Math.random(); [0.0, 1.0); Math.random() * 8.0; [0.0, 8.0); (int)(math.random() * 8.0) {0,1, 2,, 7} 2. What is the difference between pairs of numbers? (int)(math.random() * 8.0) * 10; {0,10, 20,, 70} 3. What is the first number? (int)(math.random() * 8.0) * 10 + 5; {5, 15, 25,, 75} Fall 2018 15-121 (Reid-Miller) 43