More on variables and methods

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

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

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

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

HUDSONVILLE HIGH SCHOOL COURSE FRAMEWORK

STUDENT LESSON A10 The String Class

Getting started with Java

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

More on Variables and Methods

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

Creating Strings. String Length

Strings. Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

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

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

Using Java Classes Fall 2018 Margaret Reid-Miller

Full file at

Review. Single Pixel Filters. Spatial Filters. Image Processing Applications. Thresholding Posterize Histogram Equalization Negative Sepia Grayscale

Classes and Objects Part 1

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

MATHEMATICAL FUNCTIONS CHARACTERS, AND STRINGS. INTRODUCTION IB DP Computer science Standard Level ICS3U

Robots. Byron Weber Becker. chapter 6

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

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

Java: Learning to Program with Robots

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

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

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

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

FUNDAMENTAL DATA TYPES

Lab 14 & 15: String Handling

JAVA Ch. 4. Variables and Constants Lawrenceville Press

McGill University School of Computer Science COMP-202A Introduction to Computing 1

TeenCoder : Java Programming (ISBN )

Full file at

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

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

Chapter 1 Introduction to java

Chapter 4 Mathematical Functions, Characters, and Strings

Full file at

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

Formatted Output Pearson Education, Inc. All rights reserved.

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

Lesson:9 Working with Array and String

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

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

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

Robots. Byron Weber Becker. chapter 6

Chapter 2 Elementary Programming

AP Computer Science A

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

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

Using System.out.println()

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

Chapter 3: Using Classes and Objects

CHAPTER 4 MATHEMATICAL FUNCTIONS, CHARACTERS, STRINGS

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

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

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

CSC 222: Object-Oriented Programming. Spring 2017

Program Fundamentals

COE318 Lecture Notes Week 4 (Sept 26, 2011)

Programming with Java

Eng. Mohammed Abdualal

CMPT 125: Lecture 3 Data and Expressions

Primitive Data, Variables, and Expressions; Simple Conditional Execution

CSC 222: Object-Oriented Programming. Spring 2013

Chapter 2: Data and Expressions

CS 180. Recitation 8 / {30, 31} / 2007

Computational Expression

Chapter 2: Using Data

Designing data types. Fundamentals of Computer Science I

Strings in Java String Methods. The only operator that can be applied to String objects is concatenation (+) for combining one or more strings.

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

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

Chapter 2: Using Data

STUDENT LESSON A7 Simple I/O

Lecture Set 2: Starting Java

COE318 Lecture Notes Week 5 (Oct 3, 2011)

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Unit 4: Classes and Objects Notes

Basics of Java Programming

Strings, Strings and characters, String class methods. JAVA Standard Edition

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

Lecture Set 2: Starting Java

Appendix 3. Description: Syntax: Parameters: Return Value: Example: Java - String charat() Method

String. Other languages that implement strings as character arrays

PIC 20A Number, Autoboxing, and Unboxing

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

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

TEXT-BASED APPLICATIONS

Java By Abstraction - Test-B (Chapters 1-6)

Chapter 2 ELEMENTARY PROGRAMMING

Chapter 2 Primitive Data Types and Operations. Objectives

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

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

Index COPYRIGHTED MATERIAL

DATA TYPES AND EXPRESSIONS

COMP6700/2140 Data and Types

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

Transcription:

More on variables and methods Robots Learning to Program with Java Byron Weber Becker chapter 7

Announcements (Oct 12) Reading for Monday Ch 7.4-7.5 Program#5 out

Character Data String is a java class for holding multiple characters including letters, digits, whitespace, punctuation, etc Certain characters are given special meaning in java and must be handled differently inside strings Double quotes indicate start or end of String data Single quotes are used to hold a single character The backslash is used for escape sequences Inserting a tab Inserting a line return Printing quotes Printing a backslash

The String class As with all Java classes, instances of type String are objects actually holding a reference to the memory location where their instance data is stored Therefore we should not compare them using any of the logical comparison operators : ==,!=, <, <=, >, >= There are several String methods used for comparing String objects

tostring public String tostring() Every well defined Java class has a tostring method tostring is automatically called by System.out.print or println tostring is also automatically called by string concatenation Although there is a concat method you can always use + to concatenate strings

Create a Person class that: Holds a String name Holds 3 integers for the date of birth month, day, year (always stored as 4 digits) Has a constructor that takes only the name Has a constructor that takes all data Has a setter for birth date that passes 3 ints Prints the name only Prints the name followed by the birthdate (formatted as mm/dd/yyyy leading zeros not necessary)

Data Create an Address Class String street address String city String state (just 2 letters always store in uppercase) String zip code Constructor takes all data tostring method properly returns the 2 lines of an address label Getters and setters for all data

Change the Person Class Add an Address object to the Person class data Add a constructor that passes the name and Address (as an Address object) Add a tostring method to return an address label In main, how would you print the city that a, y p y Person lives in?

Student Class Subclass of Person Adds data Number of points integer Number of credit hours - integer Student ID number all digits ULID ULID password Adds methods Getter for ULID, password, and ID Setter for password Calculate GPA as points/credit hours Pi Print an address label l tostring method for debugging purposes

Static used in a Class for Variables and Constants t Static class data (either variable or constant) is created once when the first instance is created and is accessible by all instances of the class Thus every instance of a class has the ability to change the value of static variables Used very sparingly If declared as public you can access the value using the class name double tax = Part.SALES_TAX;

Static used in a Class for methods Static methods cannot be dependent on any class data that is not also static Static methods are called using the class name NOT an instance of the class The Math class has all static methods and constants Never create a Math object Call all methods using Math.methodName() Access all constants using Math.CONSTANT

Objectives of Ch 7 Write queries to reflect the state of an object Write a driver method for your class Understand various primitive types Understand the String class Understand static vs instance variables

Driver method Code a little Test a little A driver method is a main method used simply to test the class methods Can be in a separate class (called the application class) Can be included in each individual class you write (should be removed when class is finalized) Extremely useful to programmers to find Extremely useful to programmers to find logic errors

This code has a logic error public void setmonthlysalary (int sal) { } // allow only non-negative salaries if (this.monthlysalary >= 0) { this.monthlysalary = sal; } else { System.out.println("Salary must be " + "non-negative!"); }

Becker s public class Test http://www.learningwithrobots.com/doc/index.html Methods to assist in testing code. Example usage: public static void main(string[] args) { Patron pat = new Patron(1001); Test.ckEquals("patron ID#", 1001, pat.getid()); } Each method prints a message on the console indicating whether the test passed or failed and what the expected and actual values were compared.

Primitive Types Truly hold their data not references Numeric types byte short int long float double Other Types boolean char

Type Casting Java will not allow you to write code that loses precision without explicitly stating that you intend to do so int intvalue; double doublevalue l = 5.3; intvalue = doublevalue; //error intvalue = (int)doublevalue; Type casting always truncates it does not round

Number Formatters NumberFormat class getcurrencyinstance() Forces value to print with 2 decimal places Adds a dollar sign to the front getpercentinstance() Adds a percent sign to the end Converts percentages to integers Multiplies by 100 so 7 becomes 700% getnumberinstance() Allows user to determine the pattern used to print a number Commas and significant digits are most often used Note: All returns values are String

Using NumberFormat objects double value = 2.5; NumberFormat currency = NumberFormat.getCurrencyInstance(); NumberFormat percent = NumberFormat.getPercentInstance(); NumberFormat number = NumberFormat.getNumberInstance(); System.out.println(currency.format(value)); System.out.println(percent.format(value)); System.out.println(number.format(10000000)); Output $2.50 250% 10,000,000

Columnar Output printf method is used to separate printed data into columns This method takes a variable number of arguments The first argument is the format string which The first argument is the format string which describes how the other arguments should be printed

Format String Specifiers The format string contains a format specifier for each column of data Each format specifier starts with % and is followed by an integer indicating the width of the column Positive numbers are used to indicate the data is right justified Negative numbers are used to indicate the data is left justified Each string ends with a letter indicating the kind of data in the column s is used for objects (including String data) using the tostring method to determine the output d is used for integer data f is used for floating point data (decimals)

Formatting Examples NumberFormat money = NumberFormat.getCurrencyInstance(); NumberFormat percentage = NumberFormat.getPercentInstance(); g System.out.println("12345678901234567890"); System.out.printf("%-10s%10d", "string", 5); System.out.println(); System.out.printf("%10s%-10s", "string", money.format(22.5)); System.out.println(); System.out.printf( printf("%10s%10s", "string", percentage.format(.07)); System.out.println();

Formatting output 12345678901234567890 string 5 string$22.50 string 7% "%-10s%10d", %10d" "string", " 5 "%10s%-10s", "string", money.format(22.5) "%10s%10s", "string", percentage.format(.07)

Shortcuts += -= *= /= %= ++ --

Take Care The order of operations can be confusing consider the following int value = 5; value *= 10 + 3; What is held in value after execution? This would convert to value = value * (10 + 3); NOT value = value * 10 + 3;

Character Data String is a java class for holding multiple characters including letters, digits, whitespace, punctuation, etc Certain characters are given special meaning in java and must be handled differently inside strings Double quotes indicate start or end of String data Single quotes are used to hold a single character The backslash is used for escape sequences Inserting a tab Inserting a line return Printing quotes Printing a backslash

The String class As with all Java classes, instances of type String are objects actually holding a reference to the memory location where their instance data is stored Therefore we should not compare them using any of the logical comparison operators : ==,!=, <, <=, >, >= There are several String methods used for comparing String objects

Comparing Strings int compareto(string astring) boolean equals(string astring) int comparetoignorecase(string astring) boolean equalsignorecase(string astring)

Extracting Part of a String Sometimes you just want to check on part of a String object or you want to change a single letter of a String object Extracting root words ignoring plurals, etc in a search Change a name to Title Case to ensure all names are stored correctly To do this you must understand how strings are stored and examined character by character

A Brief Intro to Arrays An array is a collection of things or elements In the case of String objects, a String is a collection of typed characters (letters, digits, punctuation marks, white space, and other special characters) Each element in an array is given an index that indicates its placement in the array Indices start at zero! The index is used to access the element This takes place inside the String class. Therefore it is not necessary that t you understand d it at this point. It will be covered in detail later Strings are stored as arrays of characters and can be manipulated element by element

Some Useful String Methods char charat(int index) returns the single character at a particular index char letter = mystring.charat(0); returns a copy of the first letter in the String int indexof(char ch) returns the index of a given character IF it occurs in the String. If the character does not occur, -1 is returned int indexof(char ch, int fromindex) searches for the given character starting from a particular index int indexof(string substring) returns the starting index of a given substring within the String int length() returns the number of characters in a string this is a very useful method

Changing Case String touppercase() returns a new String in all uppercase String tolowercase() returns a new String in all lowercase Note these methods do not change the original String object!

MoreOnTheStringClass The String constructor is not necessary String name = Bob Smith ; String name = new String( Jill Smith ); String concatenation take care System.out.println(1 + 5 + " is 6"); System.out.println("1 + 5 is " + 1 + 5);

substring public String substring(int index) Returns a portion of the calling string starting at the index and going g to the end of the string public String substring(int start, int end) Returns a portion of the calling string starting at the start index and stopping in front of the end index

More About the String Class Methods in the String class (and most Java classes) are very well named You need to know the character at a particular index charat You need to know the index of a specific character in a String indexof You want to change the case of an entire String touppercase or tolowercase You want to pull part of a String out into a new String substring Use the API to help you find methods Read the short description, but also look at the longer description http://java.sun.com/javase/6/docs/api/