Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department...

31
Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has been extracted, modified and updated from original slides of Absolute Java 3 rd Edition by Savitch; which has originally been prepared by Rose Williams of Binghamton University. Absolute Java is published by Pearson Education / Addison-Wesley. Copyright © 2007 Pearson Addison-Wesley

Transcript of Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department...

Page 1: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Comp 248 Introduction to Programming Chapter 2 - Console Input & Output

Dr. Aiman HannaDepartment of Computer Science & Software Engineering

Concordia University, Montreal, Canada

These slides has been extracted, modified and updated from original slides of Absolute Java 3 rd Edition by Savitch; which has originally been prepared by Rose Williams of Binghamton University. Absolute Java is published by

Pearson Education / Addison-Wesley.

Copyright © 2007 Pearson Addison-WesleyCopyright © 2008-2013 Aiman Hanna

All rights reserved

Page 2: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

System.out.printlnSystem.out.println for console for console outputoutput

Every invocation of Every invocation of printlnprintln ends a ends a line of outputline of outputSystem.out.println("The account has System.out.println("The account has a balance of " + balance);a balance of " + balance);

2-2

Page 3: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

printlnprintln Versus Versus printprint

Another method that can be invoked Another method that can be invoked by the by the System.outSystem.out object is object is printprint

The The printprint method is like method is like printlnprintln, , except that it does not end a lineexcept that it does not end a line

2-3

OutputFormatting1.java ((MS-Word file))

Page 4: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Formatting Output with Formatting Output with printfprintf

Starting with version 5.0, Java includes a Starting with version 5.0, Java includes a method named method named printfprintf that can be used to that can be used to produce output in a specific formatproduce output in a specific format

System.out.printfSystem.out.printf can have any number can have any number of argumentsof arguments The first argument is always a The first argument is always a format format

stringstring that contains one or more that contains one or more format format specifiersspecifiers for the remaining arguments for the remaining arguments

2-4

OutputFormatting2.java ((MS-Word file))

Page 5: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

printfprintf Format SpecifierFormat Specifier The codeThe code

double price = 19.8;double price = 19.8;

System.out.printf("Price is: System.out.printf("Price is: %10.2f", price);%10.2f", price);

System.out.println(" each");System.out.println(" each");

will output the linewill output the line

Price is: 19.80 eachPrice is: 19.80 each

2-5

Page 6: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Right and Left Justification in Right and Left Justification in printfprintf

Specifier such as Specifier such as %8.2 %8.2 will will left left alignalign the output the output

If If right alignmentright alignment is needed, then a is needed, then a ““--” sign is placed after the ” sign is placed after the %% of the of the specifier.specifier.

System.out.printf("Price is: System.out.printf("Price is: %-10.2f", price);%-10.2f", price);

OutputFormatting3.java ((MS-Word file))

2-6

Page 7: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Multiple arguments with Multiple arguments with printfprintf

It is also possible to format It is also possible to format different types with different types with printfprintf

%n%n is used for new line is used for new line

%%%% is used to escape a specifier is used to escape a specifier

2-7

OutputFormatting4.java (MS-Word file)(MS-Word file)

Page 8: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Format Specifiers for Format Specifiers for System.out.printfSystem.out.printf

2-8

Page 9: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Importing Packages and Importing Packages and ClassesClasses Libraries in Java are called Libraries in Java are called packagespackages

A package is a collection of classes that is stored in a A package is a collection of classes that is stored in a manner that makes it easily accessible to any programmanner that makes it easily accessible to any program

In order to use a class that belongs to a package, the In order to use a class that belongs to a package, the class must be brought into a program using an class must be brought into a program using an importimport statementstatement

Classes found in the package Classes found in the package java.langjava.lang are imported are imported automatically into every Java programautomatically into every Java programimport java.text.NumberFormat;import java.text.NumberFormat;

// import the NumberFormat class only// import the NumberFormat class onlyimport java.text.*; import java.text.*;

//import all the classes in package //import all the classes in package java.textjava.text

2-9

Page 10: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Console Input Using the Console Input Using the ScannerScanner ClassClass

Starting with version 5.0, Java includes a class Starting with version 5.0, Java includes a class for doing simple keyboard input named the for doing simple keyboard input named the ScannerScanner class class

In order to use the In order to use the ScannerScanner class, a program class, a program must include the following line near the start of must include the following line near the start of the file:the file:import java.util.Scannerimport java.util.Scanner

2-10

InputScanner2.java InputScanner2.java (MS-Word file)(MS-Word file)

InputScanner1.java InputScanner1.java (MS-Word file)(MS-Word file)

Page 11: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Console Input Using the Console Input Using the ScannerScanner ClassClass

The method The method nextnext reads one string reads one string of non-whitespace characters of non-whitespace characters delimited by whitespacedelimited by whitespace

The method The method nextLinenextLine reads an reads an entire line of keyboard inputentire line of keyboard input

2-11

InputScanner3.java InputScanner3.java (MS-Word file)(MS-Word file)

Page 12: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Pitfall: Dealing with the Line Pitfall: Dealing with the Line Terminator, Terminator, '\n''\n'

The method The method nextLinenextLine of the class of the class ScannerScanner reads the reads the remainder of a line of text starting wherever the last remainder of a line of text starting wherever the last keyboard reading left offkeyboard reading left off

This can cause problems when combining it with This can cause problems when combining it with different methods for reading from the keyboard such different methods for reading from the keyboard such as as nextInt, or nextnextInt, or next

Given the code,Given the code,Scanner keyboard = new Scanner(System.in);Scanner keyboard = new Scanner(System.in);int n = keyboard.nextInt();int n = keyboard.nextInt();String s1 = keyboard.nextLine();String s1 = keyboard.nextLine();String s2 = keyboard.nextLine();String s2 = keyboard.nextLine();

and the input,and the input,22Heads are better thanHeads are better than1 head.1 head.

what are the values of what are the values of nn, , s1s1, and , and s2s2??2-12

Page 13: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Pitfall: Dealing with the Line Pitfall: Dealing with the Line Terminator, Terminator, '\n''\n'

Given the code and input on the previous slideGiven the code and input on the previous slidenn will be equal towill be equal to "2""2",,s1s1 will be equal towill be equal to """", and, ands2s2 will be equal towill be equal to "heads are better than""heads are better than"

If the following results were desired instead If the following results were desired instead nn equal toequal to "2""2", , s1s1 equal toequal to "heads are better than""heads are better than", and, ands2s2 equal toequal to "1 head""1 head"

then an extra invocation of then an extra invocation of nextLinenextLine would be would be needed to get rid of the end of line character needed to get rid of the end of line character (('\n''\n') )

2-13

InputScanner4.java InputScanner4.java (MS-Word file)(MS-Word file)

Page 14: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Methods in the Class Methods in the Class ScannerScanner (Part 1 of 3)(Part 1 of 3)

2-14

Page 15: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Methods in the Class Methods in the Class ScannerScanner (Part 2 of 3)(Part 2 of 3)

2-15

Page 16: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Methods in the Class Methods in the Class ScannerScanner (Part 3 of 3)(Part 3 of 3)

2-16

Page 17: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Other Input DelimitersOther Input Delimiters The delimiters that separate keyboard input can The delimiters that separate keyboard input can

be changed when using the be changed when using the ScannerScanner class class

For example, the following code could be used to For example, the following code could be used to create a create a ScannerScanner object and change the delimiter object and change the delimiter from white-space to from white-space to "##""##"Scanner keyboard2 = new Scanner keyboard2 = new Scanner(System.in);Scanner(System.in);

Keyboard2.useDelimiter("##");Keyboard2.useDelimiter("##");

After invocation of the After invocation of the useDelimiteruseDelimiter method, method, "##""##" and not white-space will be the only input and not white-space will be the only input delimiter for the input object delimiter for the input object keyboard2keyboard2

2-17

InputScanner5.java InputScanner5.java (MS-Word file)(MS-Word file)

Page 18: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Changing the Input Delimiter Changing the Input Delimiter (Part 1 of 3)(Part 1 of 3)

2-18

Page 19: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Changing the Input Delimiter Changing the Input Delimiter (Part 2 of 3)(Part 2 of 3)

2-19

Page 20: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Changing the Input Delimiter Changing the Input Delimiter (Part 3 of 3)(Part 3 of 3)

2-20

Page 21: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Money FormatsMoney Formats Using the Using the NumberFormatNumberFormat class enables a program to class enables a program to

output amounts of money using the appropriate output amounts of money using the appropriate formatformat

The The NumberFormatNumberFormat class must first be class must first be importedimported in in order to use itorder to use itimport java.text.NumberFormatimport java.text.NumberFormat

An object of An object of NumberFormatNumberFormat must then be created must then be created using the using the getCurrencyInstance()getCurrencyInstance() method method

The The formatformat method takes a floating-point number method takes a floating-point number as an argument and returns a as an argument and returns a StringString value value representation of the number in the local currencyrepresentation of the number in the local currency

2-21

Page 22: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Money FormatsMoney Formats

2-22

import java.text.NumberFormat;import java.text.NumberFormat;

public class CurrencyFormatDemopublic class CurrencyFormatDemo{{ public static void main(String[] args)public static void main(String[] args) { { System.out.println("Default location:");System.out.println("Default location:"); NumberFormat moneyFormater =NumberFormat moneyFormater = NumberFormat.getCurrencyInstance();NumberFormat.getCurrencyInstance();

System.out.println(moneyFormater.format(19.8));System.out.println(moneyFormater.format(19.8)); System.out.println(moneyFormater.format(19.81111));System.out.println(moneyFormater.format(19.81111)); System.out.println(moneyFormater.format(19.89999));System.out.println(moneyFormater.format(19.89999)); System.out.println(moneyFormater.format(19));System.out.println(moneyFormater.format(19)); System.out.println();System.out.println(); }}}}

Page 23: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Money FormatsMoney Formats

Output of the previous programOutput of the previous program

Default location:Default location:

$19.80$19.80

$19.81$19.81

$19.90$19.90

$19.00$19.00

2-23

Page 24: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Specifying LocaleSpecifying Locale Invoking the Invoking the getCurrencyInstance()getCurrencyInstance()

method without any arguments produces method without any arguments produces an object that will format numbers an object that will format numbers according to the default locationaccording to the default location

In contrast, the location can be explicitly In contrast, the location can be explicitly specified by providing a location from the specified by providing a location from the LocaleLocale class as an argument to the class as an argument to the getCurrencyInstance()getCurrencyInstance() method method

When doing so, the When doing so, the LocaleLocale class must first be class must first be importedimportedimport java.util.Locale;import java.util.Locale;

2-24

Page 25: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

import java.text.NumberFormat;import java.text.NumberFormat;import java.util.Locale;import java.util.Locale;

public class CurrencyFormatDemopublic class CurrencyFormatDemo{{ public static void main(String[] args)public static void main(String[] args) { { System.out.println("US as location:");System.out.println("US as location:"); NumberFormat moneyFormater2 =NumberFormat moneyFormater2 = NumberFormat.getCurrencyInstance(Locale.US);NumberFormat.getCurrencyInstance(Locale.US);

System.out.println(moneyFormater2.format(19.8));System.out.println(moneyFormater2.format(19.8)); System.out.println(moneyFormater2.format(19.81111));System.out.println(moneyFormater2.format(19.81111)); System.out.println(moneyFormater2.format(19.89999));System.out.println(moneyFormater2.format(19.89999)); System.out.println(moneyFormater2.format(19));System.out.println(moneyFormater2.format(19)); }}}}

Specifying LocaleSpecifying Locale

2-25

Page 26: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Specifying LocaleSpecifying Locale

Output of the previous programOutput of the previous program

US as location:US as location:

$19.80$19.80

$19.81$19.81

$19.90$19.90

$19.00$19.00

2-26

Page 27: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Locale Constants for Currencies of Locale Constants for Currencies of Different CountriesDifferent Countries

2-27

Page 28: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

The The DecimalFormatDecimalFormat Class Class Using the Using the DecimalFormatDecimalFormat class enables a program class enables a program

to format numbers in a variety of waysto format numbers in a variety of ways The The DecimalFormatDecimalFormat class must first be class must first be importedimported

A A DecimalFormatDecimalFormat object is associated with a object is associated with a pattern when it is created using the new pattern when it is created using the new commandcommand

The object can then be used with the method The object can then be used with the method formatformat to create strings that satisfy the format to create strings that satisfy the format

An object of the class An object of the class DecimalFormatDecimalFormat has a has a number of different methods that can be used to number of different methods that can be used to produce numeral strings in various formatsproduce numeral strings in various formats

2-28

Page 29: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

The The DecimalFormatDecimalFormat Class Class (Part 1 of 3)(Part 1 of 3)

2-29

Page 30: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

The The DecimalFormatDecimalFormat Class Class (Part 2 of 3)(Part 2 of 3)

2-30

Page 31: Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

The The DecimalFormatDecimalFormat Class Class (Part 3 of 3)(Part 3 of 3)

2-31