Chapter 8: Strings and Things

Similar documents
Variables. Store information needed by the program

Programming with Java

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

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

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

AP Computer Science A

Chapter 13: Arrays of Objects

STUDENT LESSON A10 The String Class

Midterms Save the Dates!

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

String. Other languages that implement strings as character arrays

Announcements. CompSci 100e Program Design and Analysis II

Lecture Notes for CS 150 Fall 2009; Version 0.5

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

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

Lab #7 Library Classes and JUnit Testing. Daniel Amyot, Diana Inkpen, Alan. Agenda. In this lab, you are going to create your own

DM550 Introduction to Programming part 2. Jan Baumbach.

CS 1301 Ch 8, Part A

What did we talk about last time? Examples switch statements

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

Java Coding 3. Over & over again!

Comments in a Java Program. Java Overview. Identifiers. Identifier Conventions. Primitive Data Types and Declaring Variables

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

CSIS 10A Test 2 Name:_SOLUTIONS

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

Slide 1 CS 170 Java Programming 1 More on Strings Duration: 00:00:47 Advance mode: Auto

Values and Variables 1 / 30

One of Mike s early tests cases involved the following code, which produced the error message about something being really wrong:

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

Chapter 15: Object Oriented Programming

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

A+ Computer Science. strings

USING LIBRARY CLASSES

Activity 9: Object-Oriented

Accelerating Information Technology Innovation

Lab 3: Call to Order CSCI 2101 Fall 2018

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

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

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

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

Lecture Set 4: More About Methods and More About Operators

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Getting started with Java

Lab 3: Call to Order CSCI 2101 Fall 2017

Using Java Classes Fall 2018 Margaret Reid-Miller

MODULE 02: BASIC COMPUTATION IN JAVA

Midterms Save the Dates!

Basics of Java Programming

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

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

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

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

The second statement selects character number 1 from and assigns it to.

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

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Class. Chapter 6: Data Abstraction. Example. Class

- Thus there is a String class (a large class)

Full file at

Accelerating Information Technology Innovation

Exception Handling. Chapter 11. Outline. Example: The Quotient app What Are Exceptions? Java By Abstraction Chapter 11

Voice Application Specification. SBString

Notes from the Boards Set BN19 Page

CS 112 Introduction to Programming

Program development plan

CS 106 Introduction to Computer Science I

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

H212 Introduction to Software Systems Honors

Basic Computation. Chapter 2

CS251L REVIEW Derek Trumbo UNM

AP Programming - Chapter 6 Lecture

Lecture Set 4: More About Methods and More About Operators

Activity 9: Object-Oriented

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

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

Java Fall 2018 Margaret Reid-Miller

Chapter 4 Lab. Loops and Files. Objectives. Introduction

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

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

Software Practice 1 Basic Grammar

Fall 2017 CISC124 10/1/2017

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

BM214E Object Oriented Programming Lecture 8

CISC 370: Introduction to Java

What did we talk about last time? Math methods boolean operations char operations

J.43 The length field of an array object makes the length of the array available. J.44 ARRAYS

Building Java Programs

More on Strings. String methods and equality. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Compu<ng and Mathema<cs h=p://

Using System.out.println()

Index COPYRIGHTED MATERIAL

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

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

Unit 4: Classes and Objects Notes

More on Strings. Lecture 10 CGS 3416 Fall October 13, 2015

Creating Strings. String Length

Netbeans tutorial:

CS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.

The NetBeans IDE is a big file --- a minimum of around 30 MB. After you have downloaded the file, simply execute the file to install the software.

SDKs - Eclipse. SENG 403, Tutorial 2

Transcription:

Chapter 8: Strings and Things Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey

Word Of Fortune Program this will be cleared when it's working 1-2

Chapter Topics Chapter 8 discusses the following main topics: The char data type String methods: length, charat Traversal Run-time Errors/Exceptions Reading Javadoc files Looping and Counting String methods: indexof, compareto, substring Working with input files 1-3

What is the data contained in a String object? The components of a String object are letters: For example, 'a', 'b', 'X', 'Y', '@', '-', '.', and ' ' A better word for these is characters Java has a data type that stores single characters, called char char works like the other types we have seen: char ltr = 'c'; if (ltr == 'c') { System.out.println(ltr); } 1-4

The char Data Type String values appear in double quotes, like "hello" Character values appear in single quotes, like 'x' char values can contain only a single letter or symbol. Don t confuse char literals with string literals. char literals: 'a', 'Z', '%' String literals: "abc", "Z", "$4.50" 1-5

The charat method for Strings Returns the letter or symbol located at some location in the String String fruit = "banana"; char letter = fruit.charat(1); System.out.println(letter); In the above case, letter contains the value 'a' The actual first letter of a String is at location 0 char letter = fruit.charat(0); now letter contains 'b' 1-6

The length method for Strings Takes no arguments Returns the number of letters in a String String city = "New York"; int length = city.length(); System.out.println(length); Knowing length, can we find the last letter of a String? char last = city.charat(length); //ERROR The actual last letter of a String is at location length-1 char last = city.charat(length-1); now last contains 'k' 1-7

Traversing Strings We often wish to process a String letter-by-letter This pattern of processing is called a traversal. A natural way to encode a traversal is with a while statement: int index = 0; while (index < fruit.length()) { char letter = fruit.charat(index); System.out.println(letter); index = index + 1; } prints each letter on a line by itself 1-8

Trace a Traversal Loop String fruit = banana; int index = 0; while (index < fruit.length()) { char letter = fruit.charat(index); System.out.println(letter); index = index + 1; } fruit fruit. length() index index < fruit.length() letter Console 1-9

Traversing Strings Notice the condition index < fruit.length() when index equals the length of the String condition is false last true value is when index = length-1 Why the variable name index? An index specifies a member in an ordered set index indicates which letter we are talking about 1-10

Run Time Errors In Java run-time errors are called exceptions. Exceptions are thrown for illegal actions like asking for the charat with a negative index or an index > length-1 1-11

Run Time Errors In Java run-time errors are called exceptions. Exceptions are thrown for illegal actions like asking for the charat with a negative index or an index > length-1 1-12

The exception thrown from the previous example Shows the type of exception and a stack trace java.lang.stringindexoutofboundsexception: String index out of range: 6 at java.lang.string.charat(string.java:658) at BadString.getLastLetter(BadString.java:14) at BadString.processWord(BadString.java:8) at BadString.main(BadString.java:4) Exceptions are like penalty flags in sports If you know how to read them you'll get more out of the game! 1-13

In the previous slide What kind of Exception occurred, and what package is it defined in? What is the value of the index that caused the exception? What method threw the exception, and where is that method defined? What method invoked charat? In BadString.java, what is the line number where charat was invoked? 1-14

Reading Documentation Javadoc for String class http://docs.oracle.com/javase/6/docs/api/java/lang/string.html Javadoc can be found easily with google search "java string class" will take you straight to page 1-15

1-16

Decoding the Javadoc info The method's prototype: Specifies the name of the method, type of parameters, and the return type What the method does: 1-17

Comparing Strings, equals method Strings are objects Using == and <= doesn't work right with objects use equals method to check for equality 1-18

Begin Lab 8 Part A Word of Fortune! BTW You will need to repeat the main game loop as long as the two words are NOT equal To test for INequality, put a! in front of expression, for example: If you finish early, start on Assignment 8 1-19

String Topics ++ More String methods indexof touppercase, tolowercase substring Comparing Strings (equals and compareto) Looping and counting Reading from files 1-20

The indexof method for Strings indexof is the reverse of charat: charat returns the character at the desired index indexof returns the index of the desired character Use it to find where a letter appears in a String String fruit = "banana"; int index = fruit.indexof('a'); In the above example index gets the number 1 If the letter is not in the string, indexof returns -1 1-21

Another version of indexof Takes a second argument that indicates where in the string to start looking int index = fruit.indexof('a',2); In the above, index gets the number 3 If the letter is at the start index, the start index is returned int index = fruit.indexof('a',5); In the above, index gets the number 5 1-22

Converting touppercase, tolowercase Here's how we can convert the case of a String String greeting = "hello"; S print(greeting.touppercase()); HELLO Note the original value of greeting is unchanged S print(greeting); hello 1-23

Strings are immutable Once created, the value of a String object cannot change When you invoke touppercase on a String, you get a new String as a return value. For example: String name = "Alan Turing"; String uppername = name.touppercase(); uppername contains "ALAN TURING" name still contains "Alan Turing". 1-24

Selecting a substring of a String Returns a new String which is a subset of original String s1 = "hamburger"; String s2 = s1.substring(4,8); urge String s3 = "smiles"; String s4 = s2.substring(1,5); mile public String substring(int beginindex, int endindex) Returns a new string that is a substring of this string. The substring begins at the specified beginindex and extends to the character at index endindex - 1. Thus the length of the substring is endindexbeginindex. 1-25

Another version of substring Only takes a start index, goes to end of String String s1 = "hamburger"; String s2 = s1.substring(3); burger String s3 = "smiles"; String s4 = s2.substring(1); miles public String substring(int beginindex) Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string. 1-26

What value is returned by these calls? String word = "onomotopoeia"; word.indexof('m'); word.charat(word.indexof('p')); word.indexof('o',5); word.substring(5,8); word.substring(7); word.substring(2,6).touppercase(); 1-27

What value is returned by these calls? String word = "onomotopoeia"; word.indexof('m'); word.charat(word.indexof('p')); word.indexof('o',5); word.substring(5,8); word.substring(7); word.substring(2,6).touppercase(); 1-28

What value is returned by these calls? String word = "onomotopoeia"; word.indexof('m'); word.charat(word.indexof('p')); word.indexof('o',5); word.substring(5,8); word.substring(7); word.substring(2,6).touppercase(); 3 p 6 top poeia OMOT 1-29

Looping and counting The following program counts the number of times the letter a appears in a string: 1-30

Previous example uses a counter The variable count is initialized to zero and then incremented each time we find an a. To increment is to increase by one To decrement is to decrease by one After the loop, count contains the result: the total number of a s. 1-31

Increment and Decrement Operators The ++ operator adds one to the current value of an int or char The -- operator subtracts one from the current value of an int/char Neither operator works on doubles, booleans or Strings. 1-32

Redoing the previous example Using the increment operators, we can rewrite the letter-counter: 1-33

Trace a Counting Loop String fruit = banana; int index = 0, count = 0; while (index < fruit.length()) { if (fruit.charat(index)=='a'){ count++; } index++; } System.out.println("number of a's = " + count); fruit fruit. length() index fruit.charat(index ) Console 1-34

Warning with ++/-- It is a common error to write something like index = index++; // WRONG!! Syntactically legal compiler will not warn you. leaves the value of index unchanged. Often a difficult bug to track down. Remember, you can write index = index+1, or you can write index++, but you shouldn t mix them. 1-35

Comparing primitives Primitives types are: int, double, char, boolean Only contain a single value, no methods 4, 3.14, 'a', true Compare primitives using relational operators ==,!=, >, <, >=, <= Example: int x = 5; if (x == 5){ S print("the condition is true"); } 1-36

Comparing Strings, equals method Strings are objects Using == and <= doesn't work right with objects use equals method to check for equality 1-37

String compareto method Lets you determine the order of strings compareto returns: positive number if first comes after second negative number if first comes before second zero if they are the same 1-38

What is the result of these conditions? (or say if it's an error) String noun = "apple", verb = "apply"; int x = 4, y = 3; noun.equals("apple") noun.equals(verb) x.equals(y) noun < verb noun.compareto(verb)<0 x.compareto(y) noun.compareto("apple")==0 1-39

What is the result of these conditions? (or say if it's an error) String noun = "apple", verb = "apply"; int x = 4, y = 3; noun.equals("apple") noun.equals(verb) x.equals(y) noun < verb noun.compareto(verb)<0 x.compareto(y) noun.compareto("apple")==0 true false ERROR! ERROR! true ERROR true 1-40

Working with Input Files First, set up a Scanner to point to the file then you can read from the file just as you have read from the keyboard. // Setup a Scanner to read from a text file Scanner in = new Scanner(new File("in.txt")); The file being read is "in.txt" must be in same folder as your program files 1-41

Java Imports for Input Files import java.util.scanner; import java.io.file; import java.io.filenotfoundexception; the last one is to handle the run-time error where the file is not located where it is expected. 1-42

Throwing an Exception Also, your main method needs to be able to throw an exception if the file is not found: public static void main(string[] args) throws FileNotFoundException { // Needed for file operation 1-43

Example 1-44

Reading to the end of file Scanner objects have a hasnext()method true when there is still more in the file Scanner inputfile = new Scanner(new File("words.txt")); int count = 0; apple while(inputfile.hasnext()){ asterisk inputfile.next(); attack bear count++; bring } S println("file has " + count + " words"); 1-45

Find out how many words start with 's' Scanner in = new Scanner(new File("words.txt")); int count = 0; String word; while(in.hasnext()){ } word = in.next(); if (word.charat(0) == 's'){ } count++; rotor sagas samas signage tan tar tenet tone torot S println(count + " words start with s"); 1-46