Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
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
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
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))
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))
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);
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
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
Format Specifiers for Format Specifiers for System.out.printfSystem.out.printf
2-8
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
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
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
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
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') )
Methods in the Class Methods in the Class ScannerScanner (Part 1 of 3)(Part 1 of 3)
2-14
Methods in the Class Methods in the Class ScannerScanner (Part 2 of 3)(Part 2 of 3)
2-15
Methods in the Class Methods in the Class ScannerScanner (Part 3 of 3)(Part 3 of 3)
2-16
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);
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
Changing the Input Delimiter Changing the Input Delimiter (Part 1 of 3)(Part 1 of 3)
2-18
Changing the Input Delimiter Changing the Input Delimiter (Part 2 of 3)(Part 2 of 3)
2-19
Changing the Input Delimiter Changing the Input Delimiter (Part 3 of 3)(Part 3 of 3)
2-20
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
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
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;
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);
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
Locale Constants for Currencies of Locale Constants for Currencies of Different CountriesDifferent Countries
2-27
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
The The DecimalFormatDecimalFormat Class Class (Part 1 of 3)(Part 1 of 3)
2-29
The The DecimalFormatDecimalFormat Class Class (Part 2 of 3)(Part 2 of 3)
2-30
The The DecimalFormatDecimalFormat Class Class (Part 3 of 3)(Part 3 of 3)