Input and Output The system console. In the beginning … When computers were relatively expensive and rare, most users interacted with a terminal –CRT.

Slides:



Advertisements
Similar presentations
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
Advertisements

 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested.
The Print Formatting Statement … named printf. 2 Introduction to printf statements print and println statements don’t allow us to easily format output.
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
© 2006 Pearson Addison-Wesley. All rights reserved2-1 Console Input Using the Scanner Class Starting with version 5.0, Java includes a class for doing.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: IO *Standard Output *Formatting Decimal.
1 Chapter 2 JAVA FUNDAMENTALS CONT’D. 2 PRIMITIVE DATA TYPES Computer programs operate on data values. Values in Java are classified according to their.
The printf Method The printf method is another way to format output. It is based on the printf function of the C language. System.out.printf(,,,..., );
Chapter 2 Screen Output Section 2.1 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Chapter 2 Section 2.2 Console Input Using The Scanner CLASS Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska.
Input/Output  Input/Output operations are performed using input/output functions  Common input/output functions are provided as part of C’s standard.
11 Chapter 3 DECISION STRUCTURES CONT’D. 22 FORMATTING FLOATING-POINT VALUES WITH THE DecimalFormat CLASS We can use the DecimalFormat class to control.
Lesson 7: Improving the User Interface
Simple Programs from Chapter 2 Putting the Building Blocks All Together (corresponds with Chapter 2)
1 2 2 Introduction to Java Applications Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic.
Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 2 Console Input and Output Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Console Input & Output CSS 161: Fundamentals of Computing Joe McCarthy 1.
Sahar Mosleh California State University San MarcosPage 1 System.out.println for console output System.out is an object that is part of the Java language.
Slides prepared by Rose Williams, Binghamton University Chapter 2 Console Input and Output.
Chapter 2 Console Input and Output Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Computer Programming 2 Lab(1) I.Fatimah Alzahrani.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 3 Introduction to Objects and Input/Output.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
An Introduction to Java Programming and Object-Oriented Application Development Chapter 7 Characters, Strings, and Formatting.
CMSC 202 Java Console I/O. July 25, Introduction Displaying text to the user and allowing the user to enter text are fundamental operations performed.
3. FORMATTED INPUT/OUTPUT. The printf Function The first argument in a call of printf is a string, which may contain both ordinary characters and conversion.
Lecture 2 Objectives Learn about objects and reference variables.
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
Introduction to Computing Concepts Note Set 12. Writing a Program from Scratch public class SampleProgram1 { public static void main (String [] args)
Java Programming: From Problem Analysis to Program Design, 4e Chapter 3 Introduction to Objects and Input/Output.
Formatted Output (printf) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Operating System Discussion Section. The Basics of C Reference: Lecture note 2 and 3 notes.html.
More about strings in C++. String member functions The next three slides present information about functions that are members of the C++ string class.
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Slides prepared by Rose Williams, Binghamton University Console Input and Output.
Keyboard and Screen I/O (Input/Output). Screen Output  System.out is an object that is part of the Java language. (Don’t worry yet about why there is.
© 2007 Lawrenceville Press Slide 1 Chapter 4 Review Assignment Statement An assignment statement gives a value to a variable. Assignment can take several.
Copyright © Curt Hill Simple I/O Input and Output using the System and Scanner Objects.
Input and Output The system console. In the beginning … When computers were relatively expensive and rare, most users interacted with a terminal –CRT.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
CCSA 221 Programming in C INPUT AND OUTPUT OPERATIONS IN C – PART 1 1.
Streams & File Input/Output (I/O)
Chapter 2 Basic Computation
Input/Output.
Console Input and Output
TemperatureConversion
Objectives You should be able to describe: Interactive Keyboard Input
Chapter 2 Screen Output Section 2.1
Console Input and Output
INPUT STATEMENTS GC 201.
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
System.out.println for console output
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
CSS 161 Fundamentals of Computing Introduction to Computers & Java
Introduction to Classes and Methods
Introduction to Java Applications
The keyboard is the standard input device.
CS 1054 Introduction to Programming in Java
Input and Formatted Output (printf)
Presentation transcript:

Input and Output The system console

In the beginning … When computers were relatively expensive and rare, most users interacted with a terminal –CRT screen with keyboard –Remotely attached to a central, shared computer Although PCs have by and large put an end to this model, and windowing systems have largely put an end to the notion of a single screen, the model lives on in the form of the system console

Console I/O in Java Although Java is better-known for its deep support of GUI interfaces, a simple console interface is available as well We will use this model for most of the semester, as it is the most like the model used by the majority of programming languages, and will make the file I/O model easier to follow

Output methods: println We have already used the println method in several program examples The syntax is: System.out.println(arg); –Where “arg” is a String expression or an expression of one of the primitive types (int, double, char, etc.) –To output more than one value, include at least one String and use the + operator to concatenate additional values with the String

Output methods: print The print method is identical to the println method, except for the absence of “ln” and one aspect of its action: –When the println method is called, it automatically places the cursor on the next output line when it has finished outputting its argument –The print method, on the other hand, leaves the cursor at the end of the current line when it has completed its output

Example System.out.println (“Here is a brand new line:”); System.out.print (“But despite the capital letter”); System.out.print(“This is not a new line at all”); Output: Here is a brand new line But despite the capital letterThis is not a new line at all

Formatting Output We call the space occupied by an output value the field. The number of characters allocated to a field is the field width. The diagram shows output right-justified in a field width of 6 (spaces are represented by dashes)

The printf method The printf method uses the concept of field width to format console output printf takes a minimum of one argument, and may take several control string –The first argument is the control string, which specifies the format for the remaining arguments, if any –If the control string is the only argument, its contents are an ordinary string literal, and printf works exactly like print –If there are additional arguments, they follow the control string

Control Strings Integers % d Example: System.out.printf(“The result is: %5d\n”, 100); Output: The result is: 100 In the example above, the number is printed right-justified in a field of 5 spaces

Control strings Real Numbers %. f Example: System.out.printf(“You owe: $%7.2f\n”, e2); Output: You owe: $ In the example, the specified field width was one space wider than required to print the number with 2 decimal places If you specify a field width that is too narrow for the output, the field width value is simply ignored

Control strings Strings %s Example: System.out.printf("%10s%10s%10s\n", "Yours", "Mine", "Ours"); Output: Yours Mine Ours

Format Specifiers for System.out.printf

Right and Left Justification in printf The code double value = ; System.out.printf("Start%8.2fEnd", value); System.out.println(); System.out.printf("Start%-8.2fEnd", value); System.out.println(); will output the following Start 12.12End The format string "Start%8.2fEnd" produces output that is right justified with three blank spaces before the The format string "Start%-8.2fEnd" produces output that is left justified with three blank spaces after the 12.12

Standard input The System class has a member object named in which is analogous to member object out: we can use this object to read input from the keyboard The read method of System.in reads data in the form of bytes (ASCII character data); in order to read even simple type data, we need to associate System.in with an object of a class defined in the java.util.* package, Scanner We can read values of the simple numeric types from the keyboard by using the next method of a Scanner object

Example import java.util.*; … Scanner kb; double d; int i; kb = new Scanner(System.in); System.out.print(“Enter a real number: ”); d = kb.nextDouble(); System.out.print(“Enter a whole number: ”); i = kb.nextInt(); System.out.println(“You entered: ” + d + “ and ” + i);

Output from example Enter a real number: 4.35 Enter a whole number: -9 You entered 4.35 and -9

The prompt/read/echo pattern The previous example illustrates a pattern of program behavior that should be used when your program reads keyboard input: –Prompt: a message to the user requesting input; for example: System.out.print(“Enter a real number: ”); –Read: a line of code that reads the requested data; example: d = kb.nextDouble(); –Echo: Write out the data read in so user can see what is actually stored in memory; example: System.out.println(“You entered: ” + d + “ and ” + i);

Dealing with users When reading keyboard input, it is best to prompt for and read one data item at a time; while this can be tedious to program, it provides an unambiguous interface to the user – s/he knows exactly what the program expects and can proceed accordingly

Reading String data from the console To read String data, we can apply the next() method of the Scanner class; next() will read all of the text the user types until s/he hits the enter key or types another white space character, as in the example below: Scanner kb = new Scanner(System.in); String myInput; System.out.print(“Enter your name: ”); myInput = kb.next();

Reading String data from the system console The code on the previous slide will only read the first word the user types; for instance, if I typed Cathleen M. Sheller, then only the word “Cathleen” would be stored as myInput The nextLine() method can be used to read an entire line of text, as in the example below: Scanner kb = new Scanner(System.in); System.out.print (“Enter your full name: ”); String fullName = kb.nextLine()

Combining nextLine with other input methods One thing to keep in mind about nextLine is that it considers a newline character (\n) as the delimiter between one input String and another Because nextInt and nextDouble read data up to the next delimiter, an extra newline character may be left to be read This can be a problem if the next input statement is a nextLine The solution is to use two calls to nextLine instead of one when a nextLine is preceded by at nextInt or nextDouble – see page 85 for details

Dealing with users: coding defensively Even with prompts, our users can get confused and give us improper data And let’s face it, some of them are just EVIL For these reasons, it’s a good idea to do whatever we can to protect our programs from crashing in the face of incompetent or malevolent users One aspect of defensive programming is anticipating bad input

Defensive coding: reading all input as Strings Input tends to be Achilles heel of many programs The nextInt and nextDouble methods of the Scanner class don’t react well to wrong input On the other hand, nextLine, which reads input as a String, can handle just about any data you throw at it And, if nextLine is the only input method you use, you never have to worry about throwing in extra nextLine calls – each one disposes of its own terminating newline character

Wrapper classes We can read any input as a String, but most of the time we want numbers to be numbers wrapper classesWe can convert Strings into numbers by using methods of the numeric wrapper classes Each simple type has a corresponding wrapper class, as shown on the next slide

Wrapper classes For simple type: –int –double –float Use wrapper class: –Integer –Double –Float

Converting Strings to numbers Each of the wrapper classes has an associated method called a parse method that takes a String argument –For the Integer class, the name of the method is parseInt –For Double, the name is parseDouble and for Float, it is parseFloat Each method returns a value of the underlying simple data type

Example The following code reads a String, then converts it to an int value: String input; int n; Scanner kb = new Scanner(System.in); System.out.print (“Enter a number: ”); input = kb.nextLine(); n = Integer.parseInt(input);

What good is this? At the moment, not much; the parse methods will react as badly to the wrong kind of input as the input methods will The advantage will become clearer when we start looking at selection structures and can test values before attempting the conversion