CS102--Object Oriented Programming Lecture 2: – the String class – Console Input/Output – Flow of control Copyright © 2008 Xiaoyan Li.

Slides:



Advertisements
Similar presentations
 2005 Pearson Education, Inc. All rights reserved Introduction.
Advertisements

1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
 Finishing Chapter 1  This week : Chapter 2  Getting our home environment configured  Working on Assignment 1  See the website for more details! 
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CS102--Object Oriented Programming
CS102--Object Oriented Programming Lecture 5: – Arrays – Sorting: Selection Sort Copyright © 2008 Xiaoyan Li.
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Input and Output The system console. In the beginning … When computers were relatively expensive and rare, most users interacted with a terminal –CRT.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
© 2006 Pearson Addison-Wesley. All rights reserved2-1 Console Input Using the Scanner Class Starting with version 5.0, Java includes a class for doing.
Slides prepared by Rose Williams, Binghamton University Chapter 1 Getting Started 1.3 The Class String.
Slides prepared by Rose Williams, Binghamton University Chapter 3 Flow of Control if-else and switch statements.
Chapter 2 Screen Output Section 2.1 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Chapter 2 Section 2.2 Console Input Using The Scanner CLASS Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska.
Java Applications & Program Design
1 2 2 Introduction to Java Applications Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic.
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments.
Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 2 Console Input and Output Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Console Input & Output CSS 161: Fundamentals of Computing Joe McCarthy 1.
Sahar Mosleh California State University San MarcosPage 1 System.out.println for console output System.out is an object that is part of the Java language.
Slides prepared by Rose Williams, Binghamton University Chapter 2 Console Input and Output.
Chapter 2 Console Input and Output Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
A First Look at Java Chapter 2 1/29 & 2/2 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
CMSC 202 Java Console I/O. July 25, Introduction Displaying text to the user and allowing the user to enter text are fundamental operations performed.
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
Introduction to Computing Concepts Note Set 12. Writing a Program from Scratch public class SampleProgram1 { public static void main (String [] args)
Sahar Mosleh California State University San MarcosPage 1 The Class String There is no primitive type for strings in Java The class String is a predefined.
Component 4: Introduction to Information and Computer Science Unit 5: Overview of Programming Languages, Including Basic Programming Concepts Lecture 3.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
By Mr. Muhammad Pervez Akhtar
Java – Variables and Constants By: Dan Lunney. Declaring Variables All variables must be declared before they can be used A declaration takes the form:
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Slides prepared by Rose Williams, Binghamton University Console Input and Output.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Input and Output The system console. In the beginning … When computers were relatively expensive and rare, most users interacted with a terminal –CRT.
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.
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
Lecture 4 – Scanner & Style
More lO.
Input/Output.
Console Input and Output
String class.
Yanal Alahmad Java Workshop Yanal Alahmad
Chapter 2 Screen Output Section 2.1
Console Input and Output
Java Programming: From Problem Analysis to Program Design, 4e
OUTPUT STATEMENTS GC 201.
Program Style Console Input and Output
System.out.println for console output
CSS 161 Fundamentals of Computing Introduction to Computers & Java
Chapter 2: Basic Elements of Java
CMSC 202 Java Primer 2.
Introduction to Java Applications
Primitive Types and Expressions
Classes, Objects and Methods
Presentation transcript:

CS102--Object Oriented Programming Lecture 2: – the String class – Console Input/Output – Flow of control Copyright © 2008 Xiaoyan Li

Review: Programming language vs. Human Languages Observation/Conclusion – It is much easier to learn a second programming language than a second human language – Pay attention to syntax, focus on core concepts

Review: A sample program in java

Primitive Types 1-4 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Questions: Legal or illegal int a,c; double b,d; a = 3.1; b = 3; c = 3/5; b = 3/5; d = 3.0/5; How to declare a variable for a string? – “Hello everyone!”

The Class String There is no primitive type for strings in Java The class String is a predefined class in Java that is used to store and process strings Objects of type String are made up of strings of characters that are written within double quotes – Any quoted string is a constant of type String "Live long and prosper." A variable of type String can be given the value of a String object String blessing = "Live long and prosper."; 1-6 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Concatenation of Strings Concatenation: Using the + operator on two strings in order to connect them to form one longer string – If greeting is equal to "Hello ", and javaClass is equal to "class", then greeting + javaClass is equal to "Hello class" Any number of strings can be concatenated together When a string is combined with almost any other type of item, the result is a string – "The answer is " + 42 evaluates to "The answer is 42" 1-7 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

String Methods The String class contains many useful methods for string- processing applications. (Guess how many?) – A String method is called by writing a String object, a dot, the name of the method, and a pair of parentheses to enclose any arguments – If a String method returns a value, then it can be placed anywhere that a value of its type can be used String greeting = "Hello"; int count = greeting.length(); System.out.println("Length is " + greeting.length()); – Always count from zero when referring to the position or index of a character in a string 1-8 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

String Indexes 1-9 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class String (Part 1 of 8) 1-10 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class String (Part 2 of 8) 1-11 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class String (Part 3 of 8) 1-12 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class String (Part 4 of 8) 1-13 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class String (Part 5 of 8) 1-14 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class String (Part 6 of 8) 1-15 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class String (Part 7 of 8) 1-16 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class String (Part 8 of 8) 1-17 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

In-class Exercises: 1. What is the output produced by the following? String test = “abcdefg”; System.out.println(test.length()); System.out.println(test.substring(3)); System.out.println(test.charAt(1)); 2. What is the output produced by the following? System.out.println(abc\ndef); 3. What is the output produced by the following? System.out.println(abc\\ndef);

Console Input/Output System.out.println System.out.print System.out.printf the Scanner class – import java.util.Scanner – This statement tells Java to Make the Scanner class available to the program Find the Scanner class in a library of classes (i.e., Java package) named java.util

System.out.println for console output System.out is an object that is part of the Java language println is a method invoked by the System.out object that can be used for console output – The data to be output is given as an argument in parentheses – A plus sign is used to connect more than one item – Every invocation of println ends a line of output System.out.println("The answer is " + 42); 2-20 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

println Versus print Another method that can be invoked by the System.out object is print The print method is like println, except that it does not end a line – With println, the next output goes on a new line – With print, the next output goes on the same line 2-21 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Formatting Output with printf Starting with version 5.0, Java includes a method named printf that can be used to produce output in a specific format The Java method printf is similar to the print method – Like print, printf does not advance the output to the next line System.out.printf can have any number of arguments – The first argument is always a format string that contains one or more format specifiers for the remaining arguments – All the arguments except the first are values to be output to the screen 2-22 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

printf Format Specifier The code double price = 19.8; System.out.print("$"); System.out.printf("%6.2f", price); System.out.println(" each"); will output the line $ each The format string "%6.2f" indicates the following: – End any text to be output and start the format specifier ( % ) – Display up to 6 right-justified characters, pad fewer than six characters on the left with blank spaces (i.e., field width is 6 ) – Display exactly 2 digits after the decimal point (.2 ) – Display a floating point number, and end the format specifier (i.e., the conversion character is f ) 2-23 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Right and Left Justification in printf The code double value = ; System.out.printf("Start%8.2fEnd", value); System.out.println(); System.out.printf("Start%-8.2fEnd", value); System.out.println(); will output the following Start 12.12End The format string "Start%8.2fEnd" produces output that is right justified with three blank spaces before the The format string "Start%-8.2fEnd" produces output that is left justified with three blank spaces after the Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Multiple arguments with printf The following code contains a printf statement having three arguments – The code double price = 19.8; String name = "magic apple"; System.out.printf("$%6.2f for each %s.", price, name); System.out.println(); System.out.println("Wow"); will output $ for each magic apple. Wow – Note that the first argument is a format string containing two format specifiers ( %6.2f and %s ) – These format specifiers match up with the two arguments that follow ( price and name ) 2-25 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Line Breaks with printf Line breaks can be included in a format string using %n The code double price = 19.8; String name = "magic apple"; System.outprintf("$%6.2f for each %s.%n", price, name); System.out.println("Wow"); will output $ for each magic apple. Wow 2-26 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Format Specifiers for System.out.printf 2-27 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

The printf Method (Part 1 of 3) 2-28 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

The printf Method (Part 2 of 3) 2-29 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

The printf Method (Part 3 of 3) 2-30 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Formatting Money Amounts with printf A good format specifier for outputting an amount of money stored as a double type is %.2f It says to include exactly two digits after the decimal point and to use the smallest field width that the value will fit into: double price = 19.99; System.out.printf("The price is $%.2f each.") produces the output: The price is $19.99 each Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Money Formats Using the NumberFormat class enables a program to output amounts of money using the appropriate format – The NumberFormat class must first be imported in order to use it import java.text.NumberFormat – An object of NumberFormat must then be created using the getCurrencyInstance() method – The format method takes a floating-point number as an argument and returns a String value representation of the number in the local currency 2-32 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Money Formats import java.text.NumberFormat; public class CurrencyFormatDemo { public static void main(String[] args) { System.out.println("Default location:"); NumberFormat moneyFormater = NumberFormat.getCurrencyInstance(); System.out.println(moneyFormater.format(19.8)); System.out.println(moneyFormater.format( )); System.out.println(moneyFormater.format( )); System.out.println(moneyFormater.format(19)); System.out.println(); } 2-33 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Money Formats Output of the previous program Default location: $19.80 $19.81 $19.90 $ Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Specifying Locale Invoking the getCurrencyInstance() method without any arguments produces an object that will format numbers according to the default location In contrast, the location can be explicitly specified by providing a location from the Locale class as an argument to the getCurrencyInstance() method – When doing so, the Locale class must first be imported import java.util.Locale; 2-35 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Specifiying Locale import java.text.NumberFormat; import java.util.Locale; public class CurrencyFormatDemo { public static void main(String[] args) { System.out.println("US as location:"); NumberFormat moneyFormater2 = NumberFormat.getCurrencyInstance(Locale.US); System.out.println(moneyFormater2.format(19.8)); System.out.println(moneyFormater2.format( )); System.out.println(moneyFormater2.format( )); System.out.println(moneyFormater2.format(19)); } 2-36 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Specifying Locale Output of the previous program US as location: $19.80 $19.81 $19.90 $ Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Locale Constants for Currencies of Different Countries 2-38 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Importing Packages and Classes Libraries in Java are called packages – A package is a collection of classes that is stored in a manner that makes it easily accessible to any program – In order to use a class that belongs to a package, the class must be brought into a program using an import statement – Classes found in the package java.lang are imported automatically into every Java program import java.text.NumberFormat; // import theNumberFormat class only import java.text.*; //import all the classes in package java.text 2-39 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

The DecimalFormat Class Using the DecimalFormat class enables a program to format numbers in a variety of ways – The DecimalFormat class must first be imported – A DecimalFormat object is associated with a pattern when it is created using the new command – The object can then be used with the method format to create strings that satisfy the format – An object of the class DecimalFormat has a number of different methods that can be used to produce numeral strings in various formats 2-40 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Console Input Using the Scanner Class Starting with version 5.0, Java includes a class for doing simple keyboard input named the Scanner class In order to use the Scanner class, a program must include the following line near the start of the file: import java.util.Scanner This statement tells Java to – Make the Scanner class available to the program – Find the Scanner class in a library of classes (i.e., Java package) named java.util 2-41 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Console Input Using the Scanner Class The following line creates an object of the class Scanner and names the object keyboard : Scanner keyboard = new Scanner(System.in); Although a name like keyboard is often used, a Scanner object can be given any name – For example, in the following code the Scanner object is named scannerObject Scanner scannerObject = new Scanner(System.in); Once a Scanner object has been created, a program can then use that object to perform keyboard input using methods of the Scanner class 2-42 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Console Input Using the Scanner Class The method nextInt reads one int value typed in at the keyboard and assigns it to a variable: int numberOfPods = keyboard.nextInt(); The method nextDouble reads one double value typed in at the keyboard and assigns it to a variable: double d1 = keyboard.nextDouble(); Multiple inputs must be separated by whitespace and read by multiple invocations of the appropriate method – Whitespace is any string of characters, such as blank spaces, tabs, and line breaks that print out as white space 2-43 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Console Input Using the Scanner Class The method next reads one string of non-whitespace characters delimited by whitespace characters such as blanks or the beginning or end of a line Given the code String word1 = keyboard.next(); String word2 = keyboard.next(); and the input line jelly beans The value of word1 would be jelly, and the value of word2 would be beans 2-44 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Console Input Using the Scanner Class The method nextLine reads an entire line of keyboard input The code, String line = keyboard.nextLine(); reads in an entire line and places the string that is read into the variable line The end of an input line is indicated by the escape sequence '\n' – This is the character input when the Enter key is pressed – On the screen it is indicated by the ending of one line and the beginning of the next line When nextLine reads a line of text, it reads the '\n' character, so the next reading of input begins on the next line – However, the '\n' does not become part of the string value returned (e.g., the string named by the variable line above does not end with the '\n' character) 2-45 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Keyboard Input Demonstration (Part 1 of 2) 2-46 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Keyboard Input Demonstration (Part 2 of 2) 2-47 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Another Keyboard Input Demonstration (Part 1 of 3) 2-48 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Another Keyboard Input Demonstration (Part 2 of 3) 2-49 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Another Keyboard Input Demonstration (Part 3 of 3) 2-50 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Pitfall: Dealing with the Line Terminator, '\n' The method nextLine of the class Scanner reads the remainder of a line of text starting wherever the last keyboard reading left off This can cause problems when combining it with different methods for reading from the keyboard such as nextInt Given the code, Scanner keyboard = new Scanner(System.in); int n = keyboard.nextInt(); String s1 = keyboard.nextLine(); String s2 = keyboard.nextLine(); and the input, 2 Heads are better than 1 head. what are the values of n, s1, and s2 ? 2-51 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Pitfall: Dealing with the Line Terminator, '\n' Given the code and input on the previous slide n will be equal to "2", s1 will be equal to "", and s2 will be equal to "heads are better than" If the following results were desired instead n equal to "2", s1 equal to "heads are better than", and s2 equal to "1 head" then an extra invocation of nextLine would be needed to get rid of the end of line character ( '\n' ) 2-52 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Methods in the Class Scanner (Part 1 of 3) 2-53 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Methods in the Class Scanner (Part 2 of 3) 2-54 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Methods in the Class Scanner (Part 3 of 3) 2-55 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

The Empty String A string can have any number of characters, including zero characters – "" is the empty string When a program executes the nextLine method to read a line of text, and the user types nothing on the line but presses the Enter key, then the nextLine Method reads the empty string 2-56 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Other Input Delimiters The delimiters that separate keyboard input can be changed when using the Scanner class For example, the following code could be used to create a Scanner object and change the delimiter from whitespace to "##" Scanner keyboard2 = new Scanner(System.in); Keyboard2.useDelimiter("##"); After invocation of the useDelimiter method, "##" and not whitespace will be the only input delimiter for the input object keyboard Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Changing the Input Delimiter (Part 1 of 3) 2-58 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Changing the Input Delimiter (Part 2 of 3) 2-59 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Changing the Input Delimiter (Part 3 of 3) 2-60 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Flow of Control As in most programming languages, flow of control in Java refers to its branching and looping mechanisms Java has several branching mechanisms: if-else, if, and switch statements Java has three types of loop statements: the while, do- while, and for statements Most branching and looping statements are controlled by Boolean expressions – A Boolean expression evaluates to either true or false – The primitive type boolean may only take the values true or false 3-61

If-else statement An if-else statement chooses between two alternative statements based on the value of a Boolean expression if (Boolean_Expression) Yes_Statement else No_Statement An multiway if-else statement if (Boolean_Expression_1) Statement_1 else if (Boolean_Expression_2) Statement_2 else if (Boolean_Expression_n) Statement_n else Statement_For_All_Other_Possibilities

The switch Statement switch (Controlling_Expression) { case Case_Label_1: Statement_Sequence_1 break; case Case_Label_2: Statement_Sequence_2 break; case Case_Label_n: Statement_Sequence_n break; default: Default_Statement Sequence break; } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

while (Boolean_Expression) Statement Or while (Boolean_Expression) { Statement_1 Statement_2 Statement_Last } while Syntax Copyright © 2008 Pearson Addison-Wesley. All rights reserved

do Statement while (Boolean_Expression); Or do { Statement_1 Statement_2 Statement_Last } while (Boolean_Expression); do-while Syntax Copyright © 2008 Pearson Addison-Wesley. All rights reserved

for Statement Syntax and Alternate Semantics (for vs. while) 3-66

CS102– Object Oriented Programming Next lecture: Defining classes Reading Assignment: Ch.4, Ch. 5. Fist programming homework will be assigned on Wednesday.