F II 6. Using Libraries Objectives

Slides:



Advertisements
Similar presentations
Java Programming Strings Chapter 7.
Advertisements

 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
More sophisticated behaviour Using library classes to implement some more advanced functionality.
Chapter 3 Using Classes and Objects. Creating Objects A variable holds either a primitive type or a reference to an object A class name can be used as.
Some basic I/O.
Fundamental Programming Structures in Java: Strings.
Strings as objects Strings are objects. Each String is an instance of the class String They can be constructed thus: String s = new String("Hi mom!");
More sophisticated behavior Using library classes to implement some more advanced functionality 3.0.
More sophisticated behavior Using library classes to implement some more advanced functionality.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Recitation 1 CS0445 Data Structures Mehmud Abliz.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 7 Strings.
From C++ to Java A whirlwind tour of Java for C++ programmers.
More sophisticated behavior Using library classes to implement some more advanced functionality 5.0.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Can we talk?. In Hello World we already saw how to do Standard Output. You simply use the command line System.out.println(“text”); There are different.
1 CSC 201: Computer Programming I Lecture 2 B. S. Afolabi.
Java 1.5 The New Java Mike Orsega Central Carolina CC.
Strings JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight.
Strings Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and.
String Definition A String is a set of characters that behaves as a single unit. The characters in a String include upper-case and lower-case letters,
Chapter 3: Classes and Objects Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Java’s String Class.
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Java Variables, Types, and Math Getting Started Complete and Turn in Address/Poem.
CSE 1201 Object Oriented Programming Using Classes and Objects.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
String Definition A string is a set of characters that behaves as a single unit. The characters in a string include upper-case and lower- case letters,
Java String 1. String String is basically an object that represents sequence of char values. An array of characters works same as java string. For example:
Java – Variables and Constants By: Dan Lunney. Declaring Variables All variables must be declared before they can be used A declaration takes the form:
Utility classes 1.Vector class 2.Random class 3.Date class 4.Scanner.
Keyboard and Screen I/O (Input/Output). Screen Output  System.out is an object that is part of the Java language. (Don’t worry yet about why there is.
© 2007 Lawrenceville Press Slide 1 Chapter 4 Review Assignment Statement An assignment statement gives a value to a variable. Assignment can take several.
Programming Fundamentals 2: Libraries/ F II Objectives – –utilize some useful Java libraries e.g. String, Scanner, HashMap, and Random.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
import java.util.Scanner; class myCode { public static void main(String[] args) { Scanner input= new Scanner(System.in); int num1; System.out.println(“Enter.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
Lab 04-2 Objectives:  Understand what a file is.  Learn how to use the File class  Learn how to use the Scanner class to read from files  Learn about.
Introduction to programming in java
OOP (Java): Libraries/ OOP (Java) Objectives – –utilize some useful Java libraries e.g. String, Scanner, HashMap, and Random Semester.
Lecture 4 CS140 Dick Steflik. Reading Keyboard Input Import java.util.Scanner – A simple text scanner which can parse primitive types and strings using.
CompSci 230 S Programming Techniques
Strings.
Libraries CITS1001.
Yanal Alahmad Java Workshop Yanal Alahmad
CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II
Lecture Notes – Basics (Ch1-6)
CSC 1051 – Data Structures and Algorithms I
Computer Programming Methodology Input and While Loop
Java Programming: From Problem Analysis to Program Design, 4e
SELECTION STATEMENTS (1)
Primitive Types Vs. Reference Types, Strings, Enumerations
Topic 11 Scanner object, conditional execution
More sophisticated behavior
CSS161: Fundamentals of Computing
Program Style Console Input and Output
Object Oriented Programming (OOP) LAB # 8
CSS 161 Fundamentals of Computing Introduction to Computers & Java
Introduction to Classes and Methods
Chapter 2: Basic Elements of Java
Java Variables, Types, and Math Getting Started
Java so far Week 7.
Know for Quiz Everything through Last Week and Lab 7
CSC1401 Input and Output (with Files)
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
F II 2. Simple Java Programs Objectives
Presentation transcript:

242-210 F II 6. Using Libraries Objectives utilize some useful Java libraries e.g. String, Scanner, HashMap, and Random Original Slides by Dr. Andrew Davison

Topics 1. The String Class 2. The InputReader Class 3. Reading Input with Scanner 4. Maps

1. The String Class In the java.lang package

Creating a String Object Four different ways (there are more). 1 String color = "blue"; String s1 = new String("hello "); char chs[] = {‘a’, ‘n’, ‘d’, ‘y’}; String s2 = new String(chs); String s3 = s1 + s2 + " davison"; // + is string concatenation s1 "hello " 2 3 4

Testing Strings for Equality s1.equals(s2) lexicographical (dictionary) comparison returns true if s1 and s2 contain the same text s1 == s2 returns true if s1 and s2 refer to the same object Strings should always be compared with equals(). continued

t1 == t2 returns false since t1 and t2 are different objects "foo" String t1 = "foo"; String t2 = "foo"; t1 == t2 returns false since t1 and t2 are different objects t1.equals(t2) returns true since t1 and t2 contain the same text t2 "foo"

Comparing Strings returns 0 if s1 and s2 are equal s1.compareTo(s2) returns 0 if s1 and s2 are equal returns < 0 if s1 < s2; > 0 if s1 > s2 s1.startsWith("text") returns true if s1 starts with “text” s1.endsWith("text") returns true if s1 ends with “text”

Locating Things in Strings for text analysis s1.indexOf('c') returns index position of first ‘c’ in s1, otherwise -1 s1.lastIndexOf('c') returns index position of last ‘c’ in s1, otherwise -1 Both of these can also take string arguments: s1.indexOf("text")

Extracting Substrings s1.substring(5) returns the substring starting at index position 5 s1.substring(1, 4) returns substring between positions 1 and 3 note: second argument is end position + 1

Changing Strings return new String object; replace every ‘a’ by ‘d’ s1.replace('a', 'd') return new String object; replace every ‘a’ by ‘d’ s1.toLowerCase() return new String object where every char has been converted to lowercase s1.trim() return new String object where any white space before or after the s1 text has been removed

How do you Change a String? Any change to a String object creates a new object, but this can be assigned back to the existing String variable. String w = "foo"; String newW = w + "bar"; w = newW; or String w = "foo"; w = w + "bar"; w "foo"

Other String Methods There are many more String methods! e.g. s.length() Look at the Java documentation for the String class.

Strings and Arrays String[] msgs = new String[2]; msgs[0] = "hello"; msgs[1] = new String("hi"); String t = msgs[1]; t.toLowerCase(); msgs[1].toLowerCase(); t = msgs[1].toLowerCase(); What is built? What is changed?

StringBuilder A StringBuilder object is like a String, but can be modified its contents are changed in-place through calls such as append(), without the overhead of creating a new object (as happens with String) The StringBuffer class is similar to StringBuilder but is slower since it can deal with Java threads. StringBuilder sb = new StringBuilder("Andrew"); sb.append(" Davison");

The Java API Docs

2. The InputReader Class Java's name for stdin / cin continued import java.util.*; public class InputReader { private Scanner reader; public InputReader() { reader = new Scanner( System.in ); } Java's name for stdin / cin continued

public String getInput() // Read a line of text from standard input { System.out.print(">> "); // print prompt String inputLine = reader.nextLine(); return inputLine.trim().toLowerCase(); // trim spaces, and make lowercase } // end of getInput() } // end of InputReader class

Combining String Ops or String s1 = " ANDREW "; s1 = s1.trim(); // "ANDREW" s1 = s1.toLowerCase(); // "andrew" or String s1 = " ANDREW "; s1 = s1.trim().toLowerCase(); // "andrew"

4. Reading Input with Scanner The Scanner class reads tokens (words) from an input stream. The input is broken into tokens based on spaces or regular expressions the token separator can be changed The tokens can be Strings, primitive types (e.g. int, float, char, double, boolean), BigIntegers, or BigDecimals.

Read an Integer from the Keyboard Scanner sc = new Scanner(System.in); int i = sc.nextInt(); sc.close(); You specify the input token type by calling methods like nextInt(), nextDouble(), etc. continued

The nextXXX() method throws an exception (error) when the input doesn't match the expected token type. nextXXX() ignores spaces before/after the input.

ConsoleAdd.java import java.util.Scanner; public class ConsoleAdd { public static void main(String[] args) { Scanner s = new Scanner( System.in ); System.out.print("Enter first integer: ") int x = s.nextInt(); System.out.print("Enter second integer: ") int y = s.nextInt(); s.close(); System.out.println("Adding gives: " + (x+y) ); } } // end of ConsoleAdd class

Usage

Read floats from a File Scanner sc = new Scanner(new File("floats.txt")); while ( sc.hasNextFloat() ) float f = sc.nextFloat(); sc.close(); Scanner supports many nextXXX() and hasNextXXX() methods e.g. nextBoolean() and hasNextBoolean() hasNextXXX() returns true if nextXXX() would succeed.

FloatsAdd.java import java.io.*; import java.util.Scanner; public class FloatsAdd { public static void main(String[] args) { float num; float total = 0.0f; System.out.println("Openning " + args[0]); :

try { Scanner sc = new Scanner( new File(args[0]) ); while ( sc try { Scanner sc = new Scanner( new File(args[0]) ); while ( sc.hasNextFloat() ) { num = sc.nextFloat(); System.out.println(num); total += num; } sc.close(); } catch(FileNotFoundException e) { System.out.println("Error: " + args[0] + " not found"); } System.out.println("Floats total = " + total ); } } // end of FloatsAdd class

floats.txt Input File

Usage

Extract day and year from a String String sampleDate = "25 Dec 2007"; Scanner sDate = Scanner.create(sampleDate); int dom = sDate.nextInt(); // gets 25 String mon = sDate.next(); // gets "Dec" int year = sDate.nextInt(); // gets 2007 sDate.close();

4. Maps Maps are collections that contain pairs of objects. a pair consists of a key and a value A real-world Map example: a telephone book The programmer passes a key to the Map.get() method, and it returns the matching value (or null). name → phone no.

Using a Map A HashMap with Strings as keys and values A telephone book "Charles Nguyen" "(531) 9392 4587" "Lisa Jones" "(402) 4536 4674" "William H. Smith" "(998) 5488 0123" A telephone book

Coding a Map HashMap <String, String> phoneBook = new HashMap<String, String>(); phoneBook.put("Charles Nguyen", "(531) 9392 4587"); phoneBook.put("Lisa Jones", "(402) 4536 4674"); phoneBook.put("William H. Smith", "(998) 5488 0123"); String phoneNumber = phoneBook.get("Lisa Jones"); System.out.println( phoneNumber ); prints: (402) 4536 4674