Comp 248 Introduction to Programming

Similar documents
Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

Install Java Development Kit (JDK) 1.8

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

CS 106 Introduction to Computer Science I

6.1. Example: A Tip Calculator 6-1

Some Scanner Class Methods

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Introduction to Java. CS 3: Computer Programming in Java

Building Java Programs

Object-Oriented Programming in Java

Lab 5: Bank Account. Defining objects & classes

Basics of Java Programming Input and the Scanner class

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Building Java Programs

Chapter 2: Elements of Java

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Chapter 3. Input and output. 3.1 The System class

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Introduction to Java

Using Files as Input/Output in Java 5.0 Applications

Topic 11 Scanner object, conditional execution

Week 1: Review of Java Programming Basics

Introduction to Programming

Chapter 2 Introduction to Java programming

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

AP Computer Science Static Methods, Strings, User Input

Visit us at

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

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Sample CSE8A midterm Multiple Choice (circle one)

Building Java Programs

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Chapter 2 Elementary Programming

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Lecture 5: Java Fundamentals III

Carron Shankland. Content. String manipula3on in Java The use of files in Java The use of the command line arguments References:

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Programming Fundamentals I CS 110, Central Washington University. November 2015

Programming in Java. What is in This Chapter? Chapter 1

More on Objects and Classes

Part I. Multiple Choice Questions (2 points each):

Introduction to Object-Oriented Programming

Programmierpraktikum

AP Computer Science Java Subset

Interactive Programs and Graphics in Java

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Introduction to programming

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

AP Computer Science Java Mr. Clausen Program 9A, 9B

JAVA ARRAY EXAMPLE PDF

Interactive Applications (CLI) and Math

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Quick Introduction to Java

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

D06 PROGRAMMING with JAVA

IRA EXAMPLES. This topic has two examples showing the calculation of the future value an IRA (Individual Retirement Account).

JAVA.UTIL.SCANNER CLASS

Event-Driven Programming

Data Structures Lecture 1

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Reading Input From A File

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

Lecture 1 Introduction to Java

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Course Intro Instructor Intro Java Intro, Continued

1001ICT Introduction To Programming Lecture Notes

Java CPD (I) Frans Coenen Department of Computer Science

Programming and Data Structures with Java and JUnit. Rick Mercer

Programming Languages CIS 443

The following program is aiming to extract from a simple text file an analysis of the content such as:

CSE 8B Midterm Fall 2015

Java Crash Course Part I

Division of Informatics, University of Edinburgh

Arrays in Java. Working with Arrays

AP Computer Science File Input with Scanner

CS 106 Introduction to Computer Science I

13 File Output and Input

Chapter 2 Basics of Scanning and Conventional Programming in Java

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Files and input/output streams

Homework/Program #5 Solutions

Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime?

Setting Up the Site Licenses

Variables, Constants, and Data Types

J a v a Quiz (Unit 3, Test 0 Practice)

In this Chapter you ll learn:

Chapter 8. Living with Java. 8.1 Standard Output

Building Java Programs

Problem Solving. Software Engineering. Behavior. OCD in a Nutshell. Behavior. Objects Operations Algorithm. Object-Centered Design

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

Transcription:

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 Copyright 2008-2016 Aiman Hanna All rights reserved

System.out.println for console output Every invocation of println ends a line of output System.out.println("The account has a balance of " + balance); 2-2

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 OutputFormatting1.java (MS-Word file) 2-3

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 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 OutputFormatting2.java (MS-Word file) 2-4

printf Format Specifier The code double price = 19.8; System.out.printf("Price is: %10.2f", price); System.out.println(" each"); will output the line Price is: 19.80 each 2-5

Right and Left Justification in printf Specifier such as %8.2 will right-justifythe output If left-justification is needed, then a - sign is placed after the % of the specifier. System.out.printf("Price is: %-10.2f", price); OutputFormatting3.java (MS-Word file) 2-6

Multiple arguments with printf It is also possible to format different types with printf %n is used for new line %% is used to escape a specifier OutputFormatting4.java (MS-Word file) 2-7

Format Specifiers for System.out.printf 2-8

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 the NumberFormat class only import java.text.*; //import all the classes in package java.text 2-9

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 InputScanner1.java (MS-Word file) InputScanner2.java (MS-Word file) 2-10

Console Input Using the Scanner Class The method next reads one string of nonwhitespace characters delimited by whitespace The method nextline reads an entire line of keyboard input InputScanner3.java (MS-Word file) 2-11

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, or next 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-12

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') InputScanner4.java (MS-Word file) 2-13

Pitfall: You should avoid resource leak - close() the Scanner You should avoid leaving an open Scanner object behind when your program exists Scanner kb = new Scanner(System.in); : : : kb.close(); Java does not enforce it; so you will only get a warning if you do not close an opened Scanner object (or objects if you create more than one) Nonetheless, you should close it/them before your end your program 2-14

Methods in the Class Scanner (Part 1 of 3) 2-15

Methods in the Class Scanner (Part 2 of 3) 2-16

Methods in the Class Scanner (Part 3 of 3) 2-17

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 white-space to "##" Scanner keyboard2 = new Scanner(System.in); Keyboard2.useDelimiter("##"); After invocation of the usedelimiter method, "##" and not white-space will be the only input delimiter for the input object keyboard2 InputScanner5.java (MS-Word file) 2-18

Changing the Input Delimiter (Part 1 of 3) 2-19

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

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

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-22

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(19.81111)); System.out.println(moneyFormater.format(19.89999)); System.out.println(moneyFormater.format(19)); System.out.println(); 2-23

Money Formats Output of the previous program Default location: $19.80 $19.81 $19.90 $19.00 2-24

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-25

Specifying 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(19.81111)); System.out.println(moneyFormater2.format(19.89999)); System.out.println(moneyFormater2.format(19)); 2-26

Specifying Locale Output of the previous program US as location: $19.80 $19.81 $19.90 $19.00 2-27

Locale Constants for Currencies of Different Countries 2-28

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-29

The DecimalFormat Class (Part 1 of 3) 2-30

The DecimalFormat Class (Part 2 of 3) 2-31

The DecimalFormat Class (Part 3 of 3) 2-32