STUDENT LESSON A7 Simple I/O

Similar documents
BASIC INPUT/OUTPUT. Fundamentals of Computer Science

Full file at

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Java Console Input/Output The Basics. CGS 3416 Spring 2018

Introduction to Java Applications

Java Console Input/Output The Basics

AP Computer Science Unit 1. Programs

STUDENT LESSON A12 Iterations

Formatted Output (printf) CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Formatted Output Pearson Education, Inc. All rights reserved.

double float char In a method: final typename variablename = expression ;

COMP 110 Project 1 Programming Project Warm-Up Exercise

2.8. Decision Making: Equality and Relational Operators

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Introduction to Java Applications; Input/Output and Operators

FUNDAMENTAL DATA TYPES

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

First Java Program - Output to the Screen

Chapter 2: Data and Expressions

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Using Java Classes Fall 2018 Margaret Reid-Miller

int: integers, no fractional part double: floating-point numbers (double precision) 1, -4, 0 0.5, , 4.3E24, 1E-14

Full file at

when you call the method, you do not have to know exactly what those instructions are, or even how the object is organized internally

Chapter 2: Data and Expressions

Programming with Java

Hello World. n Variables store information. n You can think of them like boxes. n They hold values. n The value of a variable is its current contents

Full file at

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Section 2.2 Your First Program in Java: Printing a Line of Text

2/9/2012. Chapter Four: Fundamental Data Types. Chapter Goals

Getting started with Java

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Activity 4: Methods. Content Learning Objectives. Process Skill Goals

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Introduction to Java Unit 1. Using BlueJ to Write Programs

What did we talk about last time? Examples switch statements

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Section 2: Introduction to Java. Historical note

Topics. The Development Process

COMP 202 Java in one week

Midterm Examination (MTA)

STUDENT LESSON A10 The String Class

I. Variables and Data Type week 3

A variable is a name for a location in memory A variable must be declared

Fundamentals of Programming Session 4

Example Program. public class ComputeArea {

AP Computer Science Unit 1. Writing Programs Using BlueJ

Big Java. Fifth Edition. Chapter 3 Fundamental Data Types. Cay Horstmann

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

Primitive Data Types: Intro

Arithmetic and IO. 25 August 2017

Repetition CSC 121 Fall 2014 Howard Rosenthal

Full file at

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Introduction to Java & Fundamental Data Types

Section 2.2 Your First Program in Java: Printing a Line of Text

AP Computer Science Unit 1. Writing Programs Using BlueJ

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

Basic Programming Elements

Chapter 2: Using Data

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

Introduction to Software Development (ISD) David Weston and Igor Razgon

Chapter 17. Iteration The while Statement

2.5 Another Application: Adding Integers

AP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education

CS111: PROGRAMMING LANGUAGE II

COMP 202. Java in one week

Formatting Output & Enumerated Types & Wrapper Classes

Building Java Programs

Introduction to Computer Science Unit 2. Notes

St. Edmund Preparatory High School Brooklyn, NY

IT 374 C# and Applications/ IT695 C# Data Structures

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

CS11 Java. Fall Lecture 1

Chapter. Let's explore some other fundamental programming concepts

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Chapter 2 ELEMENTARY PROGRAMMING

Basic Computation. Chapter 2

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Chapter 3. Selections

A+ Computer Science -

ECE 122 Engineering Problem Solving with Java

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

Chapter 2: Basic Elements of Java

CS110: PROGRAMMING LANGUAGE I

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

We now start exploring some key elements of the Java programming language and ways of performing I/O

Transcription:

STUDENT LESSON A7 Simple I/O

Java Curriculum for AP Computer Science, Student Lesson A7 1 STUDENT LESSON A7 Simple I/O INTRODUCTION: The input and output of a program s data is usually referred to as I/O. There are many different ways that a Java program can perform I/O. In this lesson, we present some very simple ways to handle text input typed in at the keyboard as well as how to format text to the screen. The Advanced Placement subset does not require that you know how to use any specific input and output classes, only that you know how to use I/O in some manner. This curriculum will use the Scanner class and the printf() method provided with Java 1.5. The key topics for this lesson are: A. Reading Input with the Scanner Class B. Multiple Line Stream Output Expressions C. Formatting Output VOCABULARY: CONVERSION FLAGS PRECISION printf Scanner System.in System.out WIDTH DISCUSSION: A. Reading Input with the Scanner Class 1. Some of the programs from the preceding lessons have been written without any flexibility. To change any of the data values in the programs, it is necessary to change the variable initializations, recompile the program, and run it again. Sometimes prompting the user for a value and then processing the data is more efficient and convenient. 2. However, accepting user input in Java can be complex. Throughout this curriculum, we will use the Scanner class to make processing input easier and less tedious. 3. Just as the System class provides System.out for output, there is an object for input, System.in. Unfortunately, Java s System.in object does not directly support convenient methods for reading numbers and strings. We need to have a class sitting between the System.in object and ourselves to filter what comes through. This is what the Scanner class does. 4. Scanner is part of the java.util package, so we need to start off by adding the Scanner class to our import section. import java.util.scanner;

Java Curriculum for AP Computer Science, Student Lesson A7 2 5. Next, we create our Scanner object and pass in the System.in object. Scanner in = new Scanner(System.in); This tells the Scanner to look at the System.in object for all of its input. In Lesson A13, Exceptions and File I/O, we will learn how to change the object we pass to the Scanner so that we can read the data stored in text files. 6. Here are some example statements: int num1; double bignum; boolean istrue; num1 = in.nextint( ); bignum = in.nextdouble( ); istrue = in.nextboolean( ); When the statement num1 = in.nextint() is encountered, the program pauses until an appropriate value is entered on the keyboard. 7. Any whitespace (spaces, tabs, newline) will separate input values. When reading values, whitespace keystrokes are ignored. 8. When requesting data from the user via the keyboard, it is good programming practice to provide a prompt. An unintroduced input statement leaves the user hanging without a clue of what the program wants. For example: System.out.print("Enter an integer --> "); number = in.nextint(); B. Multiple Line Stream Output Expressions 1. We have already used examples of multiple output statements such as: System.out.println("The value of sum = " + sum); 2. When the length of an output statement exceeds one line of code, it can be broken up several different ways: System.out.println("The sum of " + num1 + " and " + num2 + " = " + (num1 + num2)); or System.out.print("The sum of " + num1 + " and " + num2); System.out.println( " = " + (num1 + num2)); 3. You cannot break up a String constant and wrap it around a line.

Java Curriculum for AP Computer Science, Student Lesson A7 3 System.out.print("A long string constant must be broken up into two separate quotes. This will NOT work."); System.out.print("A long string constant must be broken up" + " into two separate quotes. This will work."); C. Formatting Output 1. To format, we will learn a new printing method, printf(). It works similarly to the print() and println() methods that you have already been using to output text. 2. The printf() method takes two arguments. The first one is the formatting String, a special sequence of characters that tells printf() how to display the second argument. The syntax for the formatting String is: %[flags][width][.precision]conversion The % sign tells the printf method that formatting is coming. All of your formatted String constants will start with %. It does not have to be the very first thing in your String constant, just the first part of any formatted text. 3. The last part of the formatting String, conversion, is one of the most important parts. It is what determines how the printf() method reacts to a message you send it. The most important conversion tags for you to know are s, d, and f. d is used for integers (base-10 notation), f is for numbers with decimal places (doubles), and s is for String literals. The conversion tag always comes at the end of the formatting String. Conversion Tag Usage Type Example s String literals printf( %s, Sam ) d ints printf( %d, 5182) f doubles printf( %f, 2.123456) 4. Precision is very easy and straightforward. When using a formatting String with the s conversion tag, this will tell printf() the maximum number of characters to print out. When used with the f conversion tag, you can specify how many decimal places to print out, rounded to the closest number. If you don t specify how many decimal places to display with f then it will default to six places. System.out.printf( %.2s, Hello ) -> He System.out.printf( %.10s, Hello ) -> Hello System.out.printf( %.5f, Math.PI) -> 3.14159 System.out.printf( %.4f, Math.PI) -> 3.1416 System.out.printf( %f, Math.PI) -> 3.141593 5. Width tells printf() the minimum number of characters to print out. This allows for creating right-aligned lists or menus. printf() does not

Java Curriculum for AP Computer Science, Student Lesson A7 4 distinguish between normal characters and special characters (escape sequences), so Prices: and Prices:\n are two different sizes. If you want to print your data out left-aligned, you can simply add a - character to the left of the width value. Note: In the example below, the first line has a width of 11 instead of 10 to adjust for the \n error. Because numeric entries cannot use these special characters, it is better to use println() to separate lines when utilizing printf(). The example below shows one instance of using the \n character as well as doing two columns of formatted output. System.out.printf( %-10s, Name: ); System.out.printf( %11s, Price:\n ); System.out.printf( %-10s, Soda ); System.out.printf( %10.2f, 10.25); System.out.println(); System.out.printf( %-10s, Candy ); System.out.printf( %10.2f, 1.50); Run Output: Name: Price: Soda 10.25 Candy 1.50 6. Flags are special characters that give special properties to the values passed in. Adding a + sign in the formatting String will give numbers a positive or negative sign when printed. Putting in a ( will cause negative numbers to be enclosed with parentheses. The most useful of the flags is, because it will add commas into large numbers (in the correct spot for the region, i.e. Japan puts numbers into groups of four unlike the US, which puts numbers in groups of three). To get a dollar sign directly before your printed value, place the $ character directly before the % sign. System.out.printf( %,d, 12345678) -> 12,345,678 System.out.printf( $%,d, 12345678) -> $12,345,678 System.out.printf( %,(d, 12345678) -> 12,345,678 System.out.printf( %,(d, -12345678) -> (12,345,678) 7. You may put multiple arguments in one call to printf() for organizational purposes. Simply put multiple formatting Strings in the first passed argument to printf() and then add your additional arguments, separated by commas. double mysum = 123.456 System.out.printf( %10s %10.2f, Total:, mysum); 8. This curriculum uses just a few of the many things that printf() is capable of. Once you get more familiar with using the formatting options shown in this guide, you can look at the API for the Formatter class for more information on formatting Strings. The printf() method is an easy way to manage the Formatter class in a way that is very similar to the common print() and println() functions.

Java Curriculum for AP Computer Science, Student Lesson A7 5 SUMMARY/ REVIEW: These two classes, Scanner and Formatter, will be used in many programs. They provide you with the flexibility needed to start creating very robust programs. You can now interact with a user instead of simply displaying results on the screen. Go back through some of the programs you have already made and see which ones could benefit from accepting user input or formatting data. ASSIGNMENT: Lab Assignment A7.1, GroceryList Worksheet A7.1, Scanner Review Worksheet A7.2, printf Review