York University Department of Electrical Engineering and Computer Science. Regular Expressions

Similar documents
Getting started with Java

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

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

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

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

Java Bytecode (binary file)

Software and Programming 1

Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue

COMP-202: Foundations of Programming

Computational Expression

Lecture Set 2: Starting Java

Introduction to Programming Using Java (98-388)

Lecture Set 2: Starting Java

Admin. CS 112 Introduction to Programming. Recap: Exceptions. Summary: for loop. Recap: CaesarFile using Loop. Summary: Flow Control Statements

PROGRAMMING FUNDAMENTALS

CS 112 Introduction to Programming

Computer Programming, I. Laboratory Manual. Final Exam Solution

Full file at

JAVA Programming Fundamentals

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

ESc101 : Fundamental of Computing

Full file at

Chapter 2: Data and Expressions

Software and Programming 1

Grouping Objects. Primitive Arrays and Iteration. Produced by: Dr. Siobhán Drohan. Department of Computing and Mathematics

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Another Example. Other Constructs

Course Outline. Introduction to java

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

Basic Operations jgrasp debugger Writing Programs & Checkstyle

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

CSE 201 JAVA PROGRAMMING I. Copyright 2016 by Smart Coding School

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

Introduction to Java Applications

Topics. Chapter 5. Equality Operators

Computer Components. Software{ User Programs. Operating System. Hardware

data_type variable_name = value; Here value is optional because in java, you can declare the variable first and then later assign the value to it.

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

Midterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total.

4 Programming Fundamentals. Introduction to Programming 1 1

Chapter 2: Data and Expressions

Ex: If you use a program to record sales, you will want to remember data:

CS 101 Fall 2005 Midterm 2 Name: ID:

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

Simple Java Reference

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

Java Programming Language. 0 A history

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

Java+- Language Reference Manual

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

ARG! Language Reference Manual

All classes in a package can be imported by using only one import statement. If the postcondition of a method is not met, blame its implementer

COMP-202: Foundations of Programming. Lecture 5: Arrays, Reference Type, and Methods Sandeep Manjanna, Summer 2015

Lec 7. for loops and methods

Object-oriented programming in...

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

Chapter 2: Data and Expressions

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

Java Identifiers, Data Types & Variables

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

ICOM 4015 Advanced Programming Laboratory. Chapter 1 Introduction to Eclipse, Java and JUnit

1. In C++, reserved words are the same as predefined identifiers. a. True

DaMPL. Language Reference Manual. Henrique Grando

Glossary. (Very) Simple Java Reference (draft, v0.2)

Key Differences Between Python and Java

Formatting Output & Enumerated Types & Wrapper Classes

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

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

MODULE 02: BASIC COMPUTATION IN JAVA

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

Arrays: An array is a data structure that stores a sequence of values of the same type. The data type can be any of Java s primitive types:

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

CEN 414 Java Programming

CS11 Java. Fall Lecture 1

Introduction to Java & Fundamental Data Types

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof

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

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

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

Chapter 2 ELEMENTARY PROGRAMMING

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

Object Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

DATA STRUCTURE AND ALGORITHM USING PYTHON

Object-Oriented Programming

CS 11 java track: lecture 1

Choose 3 of the 1 st 4 questions (#'s 1 through 4) to complete. Each question is worth 12 points.

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

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

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

VENTURE. Section 1. Lexical Elements. 1.1 Identifiers. 1.2 Keywords. 1.3 Literals

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

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

Arrays. Introduction to OOP with Java. Lecture 06: Introduction to OOP with Java - AKF Sep AbuKhleiF - 1

CMSC131. Introduction to your Introduction to Java. Why Java?

CHAPTER 7 OBJECTS AND CLASSES

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

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

Last Class. More on loops break continue A bit on arrays

Transcription:

Regular Expressions 26 The matches Method From the API for the matches method in the String class 27 1

What is the Output? String s1 = "a"; String s2 = "b"; String regex = "a"; output.println(s1.matches(regex) + " : " + s2.matches(regex)); s1 = "a4"; s2 = "4a"; regex = "[a-z][0-9]"; output.println(s1.matches(regex) + " : " + s2.matches(regex)); s1 = "abc7"; s2 = "abcd789"; regex = "[a-z]+[0-9]"; output.println(s1.matches(regex) + " : " + s2.matches(regex)); s1 = "abc123"; s2 = "abcd1234"; regex = "[^0-9]+[0-9]{1,3}"; output.println(s1.matches(regex) + " : " + s2.matches(regex)); See DemoMatches.java 28 Example (count vowels) Write a program that inputs a string from the user. Count and output the number of vowels in the string. DemoRegexVowels.java Instructor Note: Demo from Eclipse 29 2

Example (count punctuation) Write a program that inputs a string from the user. Count and output the number of punctuation characters in the string. DemoRegexPunctuation.java Instructor Note: Demo from Eclipse 30 Example (simple time) Write a program to test whether a string entered by the user represents a time. We're looking only for certain times expressed in a certain way; namely, 3 am, 6 am, 9 am, 3 pm, 6 pm, or 9 pm. DemoRegexTime01.java Instructor Note: Demo from Eclipse 31 3

Example (logical/grouping operators) Write a program to test whether a string represents an integer in the range -25 to +25 DemoRegexIntegerRange.java Instructor Note: Demo from Eclipse 32 Homework (12-hour time) Modify DemoRegexTime01 to handle 12-hour time, according to the following examples: Correct Input 10:00 a.m. 1:59 p.m. 9:12 p.m. 11:59 a.m. 12:00 p.m. 12:00 a.m. Incorrect Input 20:00 a.m. 20:00 p.m. 9:60 p.m. 0:00 a.m. 13:25 pm Solution: DemoRegexTime02.java 33 4

Homework Write a program to test whether a string entered by the user represents a Canadian postal code. Accommodate the possibility of one space or nospace in the middle (i.e., M3J 1P3 and M3J1P3 are both valid postal codes) Solution: DemoRegexPostalCode.java Note: The first letter of a Canadian postal code must be from the set [ABCEGHJKLMNPRSTVXY]. To keep the example simple, accept any other letter in the remaining two letter positions. Accept any digit in the digit positions. 34 Command-Line Arguments By now you have probably noticed that a Java application's main method takes arguments Here's the main method signature: public static main(string[] args) args is a String array; it holds the commandline arguments entered when the app was launched The 1 st argument is args[0], the 2 nd argument is args[1], and so on 35 5

Example Modify CharFreq.java to use command-line arguments. In other words, the string and the character to search for in the string are specified on the command-line, rather through user input after the program launches. Call the program CharFreq02.java. CharFreq02.java Instructor Note: Demo from Eclipse Note: In Eclipse, use Run > Run Configuration > Arguments to specify command-line arguments. Use double quotes around an argument if it includes spaces; e.g., "Test this string" 36 length vs. length() Confusing length and length() is a common programming bug, so length used with arrays; it is an int field holding the length of the array length() used with strings; it is a method that returns an int equal to the length of the string 37 6

The split Method Now that we've discovered String arrays, we can study the split method in the String class split divides a string into a string array based on a regex Characters in the string that match the regex are used to divide the string E.g., String s = "Java is fun"; String[] words = s.split("\\s"); Creates a string array as follows: words[0] "Java" words[1] "is" words[2] "fun" 38 Example (split) Write a program that prompts the user to enter a string of text. Output a count equal to the number of tokens in the string, then output the tokens, one word per line. (Note: A "token" is any sequence of characters separated by one or more whitespace characters.) DemoSplitString.java Instructor Note: Demo from Eclipse 39 7

Example (split) Write a program that opens and reads a text file. Count and print the number of tokens in the file. DemoCountTokens.java Instructor Note: Demo from Eclipse 40 Homework Modify DemoCountTokens to count words A reasonable definition of a word is any sequence of alpha characters (a-z, A-Z) separated by nonalpha characters In order to include contractions (e.g., "don't"), consider the apostrophe an alpha character Print both the count of the number of words and the actual words. Solution: See DemoCountWords.java 41 8

Example Now it's your turn. Write a program to read a text file. Compute some interesting statistics on the contents of the file. Output the results to the console. E.g., What is the longest word? What letter appears most often? What letter appears least often? What word appears most often? (How many times?) etc. 42 Odds and Ends (things not in the text that you need to know) 43 9

Arrays Only mentioned in the text on the subject of command-line arguments and the split method in the String class Arrays are very important in Java (and other computer languages), so Arrays: Useful for storing a collection of information Operations on the collection are performed by iterating through the array Like variables, arrays must be declared and initialized 44 Array Declaration int[] numbers; // int array Brackets indicate that the variable is an array of the indicated type. The size of the array is not yet known or committed. byte[] somebytes; // byte array long[] somelongs; // long array short[] someshorts; // short array double[] realnumbers; // double array float[] morenumbers; // float array char[] somecharacters; // char array boolean[] stateflags; // boolean array Fraction[] somefractions; // object array Of course, object arrays are also possible. 45 10

Array Initialization int[] numbers = new int[6]; numbers[0] = 31; numbers[1] = 25; numbers[2] = -7; numbers[3] = 88; numbers[4] = 99; numbers[5] = 101; An empty int array with six numbers Array initialization Declaration and initialization can be combined. int numbers = { 31, 25, -7, 88, 99, 101 }; 46 Array Access int numbers = { 31, 25, -7, 88, 99, 101 }; int x = numbers[0]; Sytstem.out.println(x); Assigns the 0 th element in the numbers array to x int y = numbers[0] % numbers[1]; System.out.println(y); Use array elements in the same way as variables or literals. What is the output? (in-class demo) 47 11

Array Length (length) int[] numbers = { 31, 25, -7, 88, 99, 101 }; int x = numbers.length; System.out.printf("Array length = %d\n", x); What is the output? (in-class demo) 48 Array Length vs. Index Array indices go from 0 to length 1 Let's see PrintStream output = System.out; int[] numbers = { 31, 25, -7, 88, 99, 101 }; int x = numbers.length; output.printf("array length = %d\n", x); for (int i = 0; i < numbers.length; ++i) output.printf("i = %d, i[%d] = %d\n", i, i, numbers[i]); What is the output? (in-class demo) 49 12

Enhanced For-Loop Iterating through an array: Use a for-loop (as before), or Use an enhanced for-loop for (T variable : collection) { do-something } Works for arrays of objects or arrays of primitive data types See DemoEnhancedForLoop.java 50 Using Arrays Write a program that processes the entries in the numbers array (previous slide). Determine and output (i) the largest number, (ii) the smallest number, and (iii) the mean of the numbers. Solution: DemoUsingArrays01.java 51 13

Thank You 52 14