Lesson 1C Using the printf and String.format commands. By John B. Owen All rights reserved 2011, revised 2015

Similar documents
Base Conversion written by Cathy Saxton

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Binary Number System. 16. Binary Numbers. Base 10 digits: Base 2 digits: 0 1

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

Section 1.4 Place Value Systems of Numeration in Other Bases

Pemrograman Dasar. Basic Elements Of Java

Digital System Design Prof. D Roychoudhry Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Variables, Constants, and Data Types

Sources: On the Web: Slides will be available on:

Number Systems and Radix Conversion

Secrets of printf. 1 Background. 2 Simple Printing. Professor Don Colton. Brigham Young University Hawaii. 2.1 Naturally Special Characters

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Everything you wanted to know about using Hexadecimal and Octal Numbers in Visual Basic 6

Numbering Systems. InThisAppendix...

The programming language C. sws1 1

1. Give the 16 bit signed (twos complement) representation of the following decimal numbers, and convert to hexadecimal:

.NET Standard DateTime Format Strings

NUMBER SYSTEMS. William Stallings

CS 106 Introduction to Computer Science I

Chapter Binary, Octal, Decimal, and Hexadecimal Calculations

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

HOMEWORK # 2 SOLUTIO

CSI 333 Lecture 1 Number Systems

Binary Numbers. Binary Octal Hexadecimal

Chapter 4: Computer Codes

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Chapter 2. Binary Values and Number Systems

Chapter 7 Lab - Decimal, Binary, Octal, Hexadecimal Numbering Systems

CS 1133, LAB 2: FUNCTIONS AND TESTING

This is great when speed is important and relatively few words are necessary, but Max would be a terrible language for writing a text editor.

2 Number Systems. Source: Foundations of Computer Science Cengage Learning. Objectives After studying this chapter, the student should be able to:

Calculator Notes for the TI-Nspire and TI-Nspire CAS

Decimal to Binary Conversion

Basics of Counting. The product rule. Product rule example. 22C:19, Chapter 6 Hantao Zhang. Sample question. Total is 18 * 325 = 5850

Binary, Hexadecimal, Octal, and BCD Numbers

Positional Numbering System

Binary Representation. Number Systems. Base 10, Base 2, Base 16. Positional Notation. Conversion of Any Base to Decimal.

Teaching Pre-Algebra in PowerPoint

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

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

COMP 250 Fall 2012 lecture 2 binary representations Sept. 11, 2012

Java Basics: Data Types, Variables, and Loops

Part 1 Foundations of object orientation

Formal Languages and Automata Theory - Regular Expressions and Finite Automata -

Lecture 11: Number Systems

plc numbers Encoded values; BCD and ASCII Error detection; parity, gray code and checksums

Creating Database Tables in Microsoft SQL Server

Unit 1 Number Sense. In this unit, students will study repeating decimals, percents, fractions, decimals, and proportions.

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

PIC 10A. Lecture 7: Graphics II and intro to the if statement

CSCI 1301: Introduction to Computing and Programming Summer 2015 Project 1: Credit Card Pay Off

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

6.1. Example: A Tip Calculator 6-1

The string of digits in the binary number system represents the quantity

Oct: 50 8 = 6 (r = 2) 6 8 = 0 (r = 6) Writing the remainders in reverse order we get: (50) 10 = (62) 8

The Answer to the 14 Most Frequently Asked Modbus Questions

Number Representation

EE 261 Introduction to Logic Circuits. Module #2 Number Systems

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

3. Convert a number from one number system to another

Field Properties Quick Reference

Computers. Hardware. The Central Processing Unit (CPU) CMPT 125: Lecture 1: Understanding the Computer

MULTIPLICATION AND DIVISION OF REAL NUMBERS In this section we will complete the study of the four basic operations with real numbers.

SECTION C [short essay] [Not to exceed 120 words, Answer any SIX questions. Each question carries FOUR marks] 6 x 4=24 marks

Useful Number Systems

Ecma/TC39/2013/NN. 4 th Draft ECMA-XXX. 1 st Edition / July The JSON Data Interchange Format. Reference number ECMA-123:2009

Mathematical Induction

NUMBER SYSTEMS APPENDIX D. You will learn about the following in this appendix:

You can probably work with decimal. binary numbers needed by the. Working with binary numbers is time- consuming & error-prone.

Memory Management Simulation Interactive Lab

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Computer Science 281 Binary and Hexadecimal Review

Number Conversions Dr. Sarita Agarwal (Acharya Narendra Dev College,University of Delhi)

Sample CSE8A midterm Multiple Choice (circle one)

Lab Experience 17. Programming Language Translation

COMPUTER SCIENCE. Paper 1 (THEORY)

Sequential Program Execution

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

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

First Bytes Programming Lab 2

Binary Representation

=

Counting in base 10, 2 and 16

Chapter 3. Input and output. 3.1 The System class

ECE 122. Engineering Problem Solving with Java

LabVIEW Day 6: Saving Files and Making Sub vis

2010/9/19. Binary number system. Binary numbers. Outline. Binary to decimal

Binary Adders: Half Adders and Full Adders

Basic Programming and PC Skills: Basic Programming and PC Skills:

Chapter One Introduction to Programming

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Introduction to Data Structures

Chapter 2: Elements of Java

ASSEMBLY LANGUAGE PROGRAMMING (6800) (R. Horvath, Introduction to Microprocessors, Chapter 6)

Vim, Emacs, and JUnit Testing. Audience: Students in CS 331 Written by: Kathleen Lockhart, CS Tutor

Introduction to Java. CS 3: Computer Programming in Java

Unsigned Conversions from Decimal or to Decimal and other Number Systems

Solution for Homework 2

Chapter 1. Binary, octal and hexadecimal numbers

Preliminary Mathematics

Transcription:

Lesson 1C Using the printf and String.format commands By John B. Owen All rights reserved 2011, revised 2015

Table of Contents Objectives printf command printf examples ABCs of printf The rest of the story String variables and String.format Special Calendar feature brief intro Lesson Summary / Labs Contact Information for supplementary materials

Objective #1 The student will understand and apply some of the uses of the printf command which help control more precisely the format of program output. CS1 TEKS 126.33c2(E) improve numeric display by optimizing data visualization;

Objective #2 The student will also understand and apply the String.format method, which works in a similar way to printf. CS1 TEKS 126.33c2(E) improve numeric display by optimizing data visualization;

Objective #3 The student will receive a brief introduction to variables, how to assign values, and how to use them in conjunction with printf and String.format. CS1 TEKS 126.33c5(P) demonstrate an understanding of the concept of a variable;

Objective #4 The student will learn a little bit about a cool feature of Java called the Calendar class

History of printf The printf command has been around for quite some time, was originally part of the C and C++ programming language function libraries, and only just recently (last few years) was incorporated into the newest version of the JAVA language. It is very useful and easy to use to create specially formatted output.

Formatting output with printf Formatting your output means controlling the appearance, such as how many decimal places in a value, whether or not something is leftaligned or right-aligned, outputting a decimal value in scientific notation, and various other situations. This lesson shows to a certain degree most of the printf format functions

Two parameters for printf Unlike print or println, each of which receives only one parameter, printf requires at least two, and sometimes more. The first one is always a format string, which contains symbols and letters that have special meanings, called format specifiers. The second is an argument, or value, and when the program is executed is inserted into the place of the format specifier in the format string.

Example #1 of the printf statement The two parameters of this command are indicated. The first one is the format string containing one format specifier. The second is the data value, sometimes referred to as the argument for the format specifier.

Example #1 of the printf statement A format specifier always starts with the % sign, and is followed by a letter. The %s format specifier shown in this example is designed to receive a string data value, but actually can receive ANY type of data, and here s why.

Example #1 of the printf statement The reason that %s can receive any type of data is that all Java data types can be represented as a string, therefore when the compiler sees this situation, it automatically converts a non-string value into a String, thus enabling the %s format specifier to receive it.

Example #1 of the printf statement In this example, the string argument, George, is inserted into the position of the %s, as you can see in the output.

Example #2 - printf Perhaps this example will show the process more clearly.

Example #3 - printf Or maybe even this one The usefulness of this command will become more evident as your programs become more complex, especially as you incorporate variables (you ll learn about those soon).

Example #4 - printf In this example, there are five %s format specifiers in the format string, and all of them receive data arguments OTHER than strings, demonstrating why %s is the universal recipient format specifier in the printf family.

Example #4 - printf The argument data types in this example, in order of appearance, are: integer, decimal, boolean (true or false), null (which literally means nothing more about this later), and a single character (always in single quotes, as opposed to double quotes for strings).

Example #5 - printf Here you can see that it is possible to rearrange the order of the parameters or arguments, which in turn rearranges the output order in the same way. Compare this slide carefully with the previous one.

The ABCs of printf The next several slides discuss the myriad of format specifiers that are available with the Java printf method. HOWEVER for the most part, only three will be used on a common and regular basis - %s for strings, %d for integers, and %f for decimal values (floating point values). Master these three, and just be aware of the rest in case you ever need to use them.

The ABCs of printf Although %s can handle many different types of data values, there are other format specifiers designated for the different data types which create special output formats. Below are examples of the first six in the printf alphabet, some used more often in typical programming than others.

The ABCs of printf %a is for floating point hex values not used that often %b is for boolean values true and false not used that often in output statements %c is for characters, single letters in single quotes used some

The ABCs of printf %d is for integer values used quite often %e is to express decimal values in Scientific Notation used some %f is for decimal values used quite often

%e %f %g decimal specifiers Although %f is the primary format specifier for decimal values, all of these provide useful decimal value output formats. Carefully study the next few slides to see if you can decipher the difference between them

%e %f %g decimal specifiers Hint: Count how many total characters are in each output value.

%e %f %g decimal specifiers Notice that %e and %f always have six places after the decimal point, but %g is different.

%e %f %g decimal specifiers The output for %g always has seven total decimal places, including the decimal point!

%e %f %g decimal specifiers Now, watch carefully the output of the next three slides

%e %f %g decimal specifiers Do you see a difference?

%e %f %g decimal specifiers Do you see a dramatic difference?

%e %f %g comparison As the number of digits in the whole number portion of the value increased, the different formats adjusted accordingly. %e always output in scientific notation, always with six digits after the decimal point (using %E shows a capital letter in the output) %f always output the full value with six decimal places

%e %f %g comparison The %g output format always maintained seven total places, including the decimal point, UNTIL there were six digits in the whole number portion of the value, at which point it only output that part, omitting the fractional part altogether.

%e %f %g comparison When the front part of the value exceeded six places, the %g format switched over to scientific notation, again maintaining seven total digits in the number portion of the output.

The rest of the story The rest of the format specifiers are a bit cryptic, but will become clearer once you learn those concepts later on. %h outputs the hash code of a value %n is way to create a linefeed in a printf statement, like \n does %o outputs the octal (base eight) value of a number

The rest of the story %x outputs the hexadecimal (base sixteen) value of a number %% is an escape sequence for the % character to be output

The rest of the story Note carefully that neither %n nor %% require a matching argument in the parameter list.

String variables Let s go back to the beginning for a moment Below is an example, similar to the first one in this lesson, which first creates a String variable called s, assigns to it the value George, and then uses it in a printf statement. We ll learn in more detail about variables in a later lesson, but for now we ll keep it simple.

String variables Variables provide more flexibility, in that changes can be made in output statements more easily, as you can see in this example.

String variables The variable s can be changed, or reassigned, during the course of a program, and then reused in the output statement, but producing a different output based on the change that was made!

String.format The String.format command works just like printf. In the example below, the entire printf-style parameter list is assigned to a string variable using String.format, and then that variable is output. This process provides even more flexibility for your programs as they increase in complexity.

String.format The example below shows a brief summary of several of the concepts we have learned about formatting output. The + signs enable you to cut and reconnect strings that get too long for the editor window, but still keep them together as one long string. Study this example carefully!

printf, revisited The same technique works for printf as well

Special Calendar feature To complete your introduction to the basic features of printf, let s talk briefly about a cool Calendar feature that is quite useful. The format specifier used is %t, which must then be followed by another letter, like c, or s, or Y, just to mention a few. There are 33 different Calendar related formats available with this feature.

Special Calendar feature Here are examples of the three formats just mentioned. Also notice on line 1 of the program a new command. This is where the Calendar class lives and is necessary to include at the beginning of the program when using this feature.

Special Calendar feature Later on, a complete lesson will be devoted just to this class and ways to use it in your programming.

Lesson Summary This lesson introduced the printf command with a variety of format specifiers available for output control. It also showed how the String.format command works, using the format string process in a slightly different way, using variables.

Lesson Lab1C-1 Write a program that uses the printf and String.format commands to output twice a sentence of your own creation, similar to the cherry tree sentence you saw earlier in the lesson, once using String.format, and then again using printf.

Lesson Lab1C-1 You are to use three variables (as shown in earlier program examples): a string, an int, and a boolean, using all three in a sentence using the printf format specifiers.

Lesson Lab1C-1 First assign beginning values to each variable, build a sentence using printf. Then reassign the variables with different values, using the String.format process to assign it to a string variable, and then to output that sentence.

Lesson Lab1C-1 Below is an example, with the source code provided on the next slide.

Lesson Lab1C-1 Here is the source code for the previous example. Use it to help you create your own sentences.

Lesson Lab1C-2 For this lab, assign your name to a String variable, create a Calendar object as shown earlier in the lesson, and output your name with the current date and time, like this:

Lesson Lab1C-2 Here is the source code for this program.

Lesson Lab1C-3 Write a program to demonstrate the use of the %e, %f, and %g formats for decimal values. Create a double variable and assign to it a very large decimal value. Output that value in all three formats using printf. Reassign to the variable a very small decimal value, and then output in all three formats, this time using the String.format process.

Lesson Lab1C-3 Here is an example, with the source code shown.

CONGRATULATIONS! You can now more precisely control the format of your program output using the special printf and String.format commands. You also know about String variables. Now go on to Lesson 1D for more about printf.

Thanks, and have fun! To order supplementary materials for all the lessons in this package, including lesson examples, lab solutions, quizzes, tests, and unit reviews, visit the O(N)CS Lessons website, or contact me at John B. Owen captainjbo@gmail.com