CSE 21 Intro to Computing II. JAVA Objects: String & Scanner

Similar documents
CSE 21 Intro to Computing II. Inheritance

CSE 21 Intro to Computing II. Post-Midterm Review

Today s plan Discuss the Bb quiz 1 Clarify Lab 1 Review basic Java materials Classes, Objects, Interfaces Strings Java IO. Understanding Board

Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs

Programming with Java

Today s plan Discuss the Lab 1 Show Lab 2 Review basic Java materials Java API Strings Java IO

CS 101 Exam 1 Spring 200 Id Name

Full file at

Simple Java Input/Output

Introduction to Computer Programming

Programming with Java

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

Full file at

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

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

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java

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

Intro to Computer Science II

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

what are strings today: strings strings: output strings: declaring and initializing what are strings and why to use them reading: textbook chapter 8

MIDTERM REVIEW. midterminformation.htm

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

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

Building Java Programs

Full file at

Chapter 12 Strings and Characters. Dr. Hikmat Jaber

Software Practice 1 - File I/O

ECE 122 Engineering Problem Solving with Java

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

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

CMPSCI 187: Programming With Data Structures. Lecture #24: Files and a Case Study David Mix Barrington 2 November 2012

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

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

String related classes

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

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

5/29/2006. Announcements. Last Time. Today. Text File I/O Sample Programs. The File Class. Without using FileReader. Reviewed method overloading.

First Java Program - Output to the Screen

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

Language Reference Manual

H212 Introduction to Software Systems Honors

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

Using Java Classes Fall 2018 Margaret Reid-Miller

Mid Term Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: Sunday November 3, 2013 Total Marks: 50 Obtained Marks:

Classes Basic Overview

COMP String and Console I/O. Yi Hong May 18, 2015

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

CSEN202: Introduction to Computer Science Spring Semester 2017 Midterm Exam

Java Input/Output. 11 April 2013 OSU CSE 1

Introducing arrays. Week 4: arrays and strings. Creating arrays. Declaring arrays. Initialising arrays. Declaring and creating in one step

Midterms Save the Dates!

Computer Science 145 Midterm 1 Fall 2016

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

CSE 1223: Exam II Autumn 2016

Notes from the Boards Set BN19 Page

COMP-202: Foundations of Programming. Lecture 12: Linked List, and File I/O Sandeep Manjanna, Summer 2015

Place your name tag here

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

CSE 113 A. Announcements - Lab

Strings, Arrays, A1. COMP 401, Spring 2015 Lecture 4 1/20/2015

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

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger.

Introductory Mobile Application Development

Software Practice 1 Basic Grammar

CS 101 Fall 2005 Midterm 2 Name: ID:

Computer Programming, I. Laboratory Manual. Experiment #5. Strings & Text Files Input

More Data Types. The Char Data Type. Variable Declaration. CS200: Computer Science I. Module 14 More Data Types

BCIS 3630 Dr. GUYNES SPRING 2018 TUESDAY SECTION [JAN version] GRADER COURSE WEBSITE

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

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

CS 1301 Ch 8, Part A

CS 101 Spring 2007 Midterm 2 Name: ID:

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

ASSIGNMENT 4 Classes and Objects

CS Programming I: Using Objects

CS163/164 Final Exam Study Session

Dining philosophers (cont)

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

CST242 Strings and Characters Page 1

Account joeacct = new Account (100, new Account (500)); Account joeacct = new Account (100, new Account (500, null));

Introduction to Programming Using Java (98-388)

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Solution to Section #3 Portions of this handout by Eric Roberts, Mehran Sahami, Marty Stepp, Patrick Young and Jeremy Keeshin

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

CS 200 File Input and Output Jim Williams, PhD

AP Computer Science A

Variables of class Type. Week 8. Variables of class Type, Cont. A simple class:

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision

CS Programming I: Using Objects

Chapter 2: Data and Expressions

1.00 Lecture 30. Sending information to a Java program

B. Subject-specific skills B1. Problem solving skills: Supply the student with the ability to solve different problems related to the topics

Programming Assignment Comma Separated Values Reader Page 1

B.V. Patel Institute of BMC & IT, UTU 2014

HST 952. Computing for Biomedical Scientists Lecture 8

Fall 2017 CISC124 10/1/2017

Text User Interfaces. Keyboard IO plus

CS 106A Midterm Review. Rishi Bedi, adapted from slides by Kate Rydberg and Nick Troccoli Summer 2017

Chapter 4 Classes in the Java Class Libraries

Transcription:

CSE 21 Intro to Computing II JAVA Objects: String & Scanner 1

Schedule to Semester s End Week of 11/05 - Lecture #8 (11/07), Lab #10 Week of 11/12 - Lecture #9 (11/14), Lab #11, Project #2 Opens Week of 11/19 - Lecture Review (11/21), NO LAB Week of 11/26 - Lecture #11 (11/28), Lab #12 Week of 12/03 - Final Review, Lab #13, Project #2 Due Final Exam: December 12 th from 3:00 to 6:00pm Project #1 Available on Friday November 16 th at 11:55pm Due on Monday December 3 rd at 11:55pm Work alone or in a team of 2 Every student must submit the project Worth 7.5% of your overall grade Understanding Lecture Concepts Code samples: UCMCROPS->Resources->CodeSamples 2

Class String A string is an object containing one or more characters, treated as a unit. Strings are objects. You can think of them as classes that are already available for you to use. The simplest way to create a string is a string literal, which is a series of characters between quotation marks. Example: This is a string literal. You have already used string literals inside print statements. 3

Creating Strings To create a String: First, declare a String object (this is the same way you would declare another data type). Then, assign the String using a string literal or the new operator. Examples: String s1, s2; // Create two String objects s1 = "This is a test."; // Assign to String Literal s2 = new String(); // Create a blank string These steps can be combined on a single line: String s3 = "String 3."; // All together 4

Strings are Very much like arrays! Think of a String as an array of characters Examples: String s1 = Test"; char [] s2 = { C, S, E, 2, 1 }; Accessing characters of the String is done using the charat function (instead of []) Examples: System.out.println(s1.charAt(0) + + s1.charat(1)); System.out.println(s2[0] + + s2[1]); Output: T e C S 5

Strings == arrays of chars! Indices start with 0 Function length()returns the number of chars String astring = new String(); int [] anarray = new int[]; astring.length() // We call a the function length() anarray.length // We get the variable length() Each character is defined by a code (or number) that represents one character The ASCII table defines these codes ASCII stands for American Standard Code for Information Interchange 6

The ASCII table 7

Example of ASCII codes String str = aabcdbcd ; System.out.println(str.charAt(0)); System.out.println((int)str.charAt(0)); for(int i=0; i<str.length(); i++) System.out.print((int)str.charAt(i) +, ); Output a 97 97,65,98,99,100,66,67,68 Note: different codes for upper and lower case! A!= a 8

Comparing String characters We can still use the charat method to get the character Checking if two String are the same String s1 = my string ; String s2 = my string ; if(s1.length()!= s2.length()) System.out.println( NO ); else { for(int i = 0; i < s1.length() ; i++) if( s1.charat(i)!= s2.charat(i)) { System.out.println( NO ); return; } System.out.println( YES );} ASCII codes are used for comparison if (s1.charat(i) == + ) // Checks of character i is + if (s1.charat(i) <= Z && s1.charat(i) >= A ) // If char i is A-Z if (s1.charat(i) <= z && s1.charat(i) >= a ) // If char i is a-z 9

Strings work like other Objects new operator allows us to create objects: String s1 = new String; int [] a = new int[]; We manipulate objects with variables that represent the objects! s1 and a are variable names for a String and an array (of int)! We access functions of objects using the member access (dot) operator sharp.getname(); sharp.setamount(input.nextint()); We can also access String functions using the member access (dot) operator: String s1 = my string ; s1.charat(2); 10

Useful Function: Substring A substring is a portion of a String. The String function substring creates a new String object containing a portion of another String. The function can be called two different ways: s.substring(int startindex); // From <start> to s.length() s.substring(int startindex, int endindex);// <start> to <end> NOTE: IT DOES NOT INCLUDE endindex! This method returns another String object containing the characters from start to end (or the end of the string). 11

Substring Example Examples: String s = "abcdefgh"; String s1 = s.substring(3); String s2 = s.substring(3,6); String s3 = s.substring(1,3); String s4 = s2.substring(1,2); Substring s1 contains "defgh", and substring s2 contains "def". Substring s4 is assigned a substring of s2 Reminder: indices start at 0 s1 s3 s "defgh" "abcdefgh" s.substring(3) s.substring(3,6) bc" s2 "def" s4 "e" 12

Useful Function: Concat The String function concat creates a new String object containing the contents of two strings. The form of this function is: s1.concat(string s2); // Combine s1 and s2 This method returns a String object containing the contents of s1 followed by the contents of s2. 13

Concatenating Strings: Example Example: String s1 = "abc"; String s2 = def ; System.out.println(s1); System.out.println(s2); String s3 = s1.concat(s2); String s4 = s2.concat(s1); System.out.println(s1); System.out.println(s2); System.out.println(s3); System.out.println(s4); Output: abc def abc def abcdef defabc 14

Using + for Concatenation Example: String s1 = "abc"; String s2 = def ; System.out.println(s1); System.out.println(s2); String s3 = s1 + s2; // This was s1.concat(s2) String s4 = s2 + s1; // This was s2.concat(s1) System.out.println(s1); System.out.println(s2); System.out.println(s3); System.out.println(s4); Output: abc def abc def abcdef defabc 15

Selected Additional String Methods 16

Scanners Read from User: Scanner kdb = new Scanner (System.in); Pass System.in as parameter to Scanner constructor You can also pass a string as a parameter String example = This is an example ; Scanner line = new Scanner (example); Scanner Functions: next() kdb.next(); line.next(); // get next input word from keyboard // get next input word from string example Scanner Functions: hasnext() line.hasnext() ; check if there is another word in string example Returns a Boolean value (true or false)

Using Scanners to Parse Strings String example = This is an example ; Scanner line= new Scanner (example); while (line.hasnext()) { System.out.println(line.next()); } Note: delimiting character is a space ( ) be default next() function will look for a word until deliminating character is found OUTPUT This is an example

Parsing Strings with Delimiter String example = This,is,an example, with custom,delimiter ; Scanner line = new Scanner (example); line.usedelimiter( [,] ); // Tell scanner to use, as the delimiter while (line.hasnext()) { System.out.println(line.next()); } Delimiting character is comma, NOT a space:, OUTPUT This is an example with custom delimiter

Multiple Delimit Characters String example = + This,is+ an,example ; Scanner input = new Scanner (example); input.usedelimiter( [,+] ); while (input.hasnext()) { System.out.println(input.next()); } Delimiting characters are comma and plus :, + OUTPUT: This is an example

Reading/Processing Files import java.io.*; // Top of your file String filename = nums.txt ; Scanner input = new Scanner (new FileReader(filename)); input.usedelimiter( [\r] ); // use tab and carriage return while (input.hasnext()) { System.out.println(input.next()); } input.close(); This code segment reads a file and outputs its contents line by line Exceptions must be handled when reading files: FileNotFoundException NoSuchElementException

Reading a CSV file import java.io.*; System.out.print("Enter the file name: "); Scanner kdb = new Scanner(System.in); String filename = kdb.next(); try { // TRY it out Scanner input = new Scanner (new FileReader(filename)); while (input.hasnextline()) { Scanner line = new Scanner(input.nextLine()); line.usedelimiter( [,] ); // Tab delimited file while (line.hasnext()){ System.out.print(line.next()); // Read each token System.out.println(); // Done reading one line } } input.close(); } catch (FileNotFoundException e){ // Catch error System.out.println( File could not be found ); } catch (NoSuchElementException e) { // Catch error System.out.println( Tried to use next, with nothing to get ); }

Different Scanner Functions while (input.hasnextline()) { Scanner line = new Scanner(input.nextLine()); line.setdelimiter( [\t\r] ); short s = line.nextshort(); int i = line.nextint(); double d = line.nextdouble(); float f = line.nextfloat(); String str = line.next(); char c = line.next().charat(0); String rest = line.nextline(); } 23

Filenames and Paths String s; s = myfile.txt ; // in current folder s =../myfile.txt ; // previous folder // (relative path) s = C:/tmp/myfile.txt ; // full path specified s = C:\temp-file.txt ; // Error! (\t is a tab!) s = C:\\tmp\\myfile.txt ; // Ok in windows Scanner input = new Scanner (new FileReader(s)); 24