Chapter 3: Introduction to Objects and Input/Output

Slides:



Advertisements
Similar presentations
 2005 Pearson Education, Inc. All rights reserved Introduction.
Advertisements

1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Introduction to Objects and Input/Output
Dialogs. Displaying Text in a Dialog Box Windows and dialog boxes –Up to this our output has been to the screen –Many Java applications use these to display.
Objectives Learn about objects and reference variables Explore how to use predefined methods in a program.
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
COMP 14 Introduction to Programming Miguel A. Otaduy May 17, 2004.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 28, 2005.
COMP 14 Introduction to Programming Mr. Joshua Stough February 2, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 29, 2005.
COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004.
Chapter 3: Introduction to Objects and Input/Output.
Warm-Up: Monday, March 3 List all devices you can think of that can be used to input information into the computer.
11 Chapter 3 DECISION STRUCTURES CONT’D. 22 FORMATTING FLOATING-POINT VALUES WITH THE DecimalFormat CLASS We can use the DecimalFormat class to control.
Simple Programs from Chapter 2 Putting the Building Blocks All Together (corresponds with Chapter 2)
 Pearson Education, Inc. All rights reserved Formatted Output.
1 2 2 Introduction to Java Applications Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
CIS 260: App Dev I. 2 Objects and Reference Variables n Predefined Java classes you have used:  String —for defining and manipulating strings  Integer.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
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.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 3 Introduction to Objects and Input/Output.
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.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Java Programming: From Problem Analysis to Program Design, 5e Chapter 2 Basic Elements of Java.
Chapter 2 – Continued Basic Elements of Java. Chapter Objectives Type Conversion String Class Commonly Used String Methods Parsing Numeric Strings Commonly.
File Input/Output. 2Java Programming: From Problem Analysis to Program Design, 3e File Input/Output File: area in secondary storage used to hold information.
Chapter 2: Java Fundamentals Type conversion,String.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 2 - Introduction to Java Applications Outline 2.1Introduction 2.2A Simple Program: Printing a.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Java Fundamentals 5. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Objectives ► Become familiar with the class String ► ► Learn how to use input and output dialog boxes in a program ► ► Learn how to tokenize the input.
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 
GUI Graphical User Interface Each onscreen component and window is an object Object interaction makes communication and scoping challenging Event-driven.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 3 Introduction to Objects and Input/Output.
CSCI 51 Introduction to Computer Science Joshua Stough February 3, 2009.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Java Fundamentals 4. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 3: Input/Output Samples.
28 Formatted Output.
Java Fundamentals 4.
Topics Designing a Program Input, Processing, and Output
File Input / Output.
Java Programming Lecture 2
Chapter 7 User-Defined Methods.
Outline Creating Objects The String Class Packages Formatting Output
Objectives You should be able to describe: Interactive Keyboard Input
Yanal Alahmad Java Workshop Yanal Alahmad
2.5 Another Java Application: Adding Integers
Java Programming: From Problem Analysis to Program Design, 4e
OUTPUT STATEMENTS GC 201.
INPUT STATEMENTS GC 201.
IDENTIFIERS CSC 111.
API, Wrapper classes, printf, and methods
Chapter 3: Introduction to Objects and Input/Output
Chapter 2 - Introduction to Java Applications
Chapter 2: Basic Elements of Java
A First Book of ANSI C Fourth Edition
Chapter 3: Introduction to Objects and Input/Output
Chapter 3 Input output.
Introduction to Java Programming
Introduction to Java Applications
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Presentation transcript:

Chapter 3: Introduction to Objects and Input/Output Java Programming: Program Design Including Data Structures

Chapter Objectives Learn about objects and reference variables Explore how to use predefined methods in a program Become familiar with the class String Learn how to use input and output dialog boxes in a program Explore how to format the output of decimal numbers with the String method format(…) Become familiar with file input and output Java Programming: Program Design Including Data Structures

Object and Reference Variables Declare a reference variable of a class type Allocate memory space for data Instantiate an object of that class type Store object address in a reference variable Java Programming: Program Design Including Data Structures

Object and Reference Variables (continued) int x; //Line 1 String str; //Line 2 x = 45; //Line 3 str = "Java Programming"; //Line 4 Java Programming: Program Design Including Data Structures

Object and Reference Variables (continued) String str; str = "Hello there!"; Java Programming: Program Design Including Data Structures

Object and Reference Variables (continued) Primitive type variables directly store data into their memory space (int, long, double, float, boolean, …) Reference variables store the address of the object containing the data An object is an instance of a class; use new to instantiate an object Java Programming: Program Design Including Data Structures

Using Predefined Classes and Methods in a Program Many predefined packages, classes, and methods Library: A collection of packages Package: Contains several classes Class: Contains attributes & methods Method: A set of instructions Java Programming: Program Design Including Data Structures

Using Predefined Classes and Methods in a Program To use a method you must know: Name of the class containing the method (Math) Name of the package containing the class (java.lang) Name of the method (pow); it has two parameters Math.pow(x, y) [ same as xy ] Java Programming: Program Design Including Data Structures

Using Predefined Classes and Methods in a Program Example method call: import java.lang.*; //imports package ... Math.pow(2, 3); //calls power method //in class Math Dot (.)operator: accesses the method in the class Java Programming: Program Design Including Data Structures

Some Java classes for a complete list see: http://java.sun.com/j2se/1.4.2/docs/api/ java.applet java.awt java.awt.color java.awt.datatransfer java.awt.dnd java.awt.event java.awt.font java.awt.geom java.awt.im java.awt.im.spi java.awt.image java.awt.image.renderable java.awt.print java.beans java.beans.beancontext java.io java.lang java.lang.ref java.lang.reflect java.math java.net java.nio java.nio.channels java.nio.channels.spi java.nio.charset java.nio.charset.spi java.rmi java.rmi.activation java.rmi.dgc java.rmi.registry java.rmi.server java.security java.security.acl java.security.cert java.security.interfaces java.security.spec java.sql java.text java.util java.util.jar java.util.logging java.util.prefs java.util.regex java.util.zip javax.accessibility javax.crypto … Java Programming: Program Design Including Data Structures

Some Methods in java. lang. Math for a complete list see: http://java ABS(number) ACOS(double) ASIN(double) ATAN(double) ATAN2(double1, double2) CEILING(double) COS(double) COT(double) DEGREES(number) ** EXP(double) FLOOR(double) ** not generally available LOG(double) LOG10(double) ** MOD(integer1, integer2) PI() POWER(number, power) RADIANS(number) RAND(integer) ROUND(number, places) SIGN(number) SIN(double) SQRT(double) TAN(double) TRUNCATE (number, places) Java Programming: Program Design Including Data Structures

The class String String variables are reference variables Given: String name; Equivalent statements: name = new String("Lisa Simpson"); name = "Lisa Simpson"; name Lisa Simpson Java Programming: Program Design Including Data Structures

The class String String object is an instance of class String A String object with the value "Lisa Simpson" is instantiated The address of the object is stored in name new is unnecessary when instantiating Java strings String methods are called using the dot operator theString.theMethod(…) Java Programming: Program Design Including Data Structures

Commonly Used String Methods sentence = “Programming with Java” 012345678901234567890 Java Programming: Program Design Including Data Structures

Commonly Used String Methods (continued) sentence = “Programming with Java” 012345678901234567890 Java Programming: Program Design Including Data Structures

Commonly Used String Methods (continued) sentence = “Programming with Java” 012345678901234567890 Java Programming: Program Design Including Data Structures

Commonly Used String Methods (continued) sentence = “Programming with Java” 012345678901234567890 Java Programming: Program Design Including Data Structures

Commonly Used String Methods (continued) public class PlayingWithStrings1 { public static void main(String[] argv) String sentence = "Programming with Java"; // same as: String sentence = new String("Programming with Java"); System.out.println ("sentence: " + sentence); System.out.println ("sentence.charAt(3) " + sentence.charAt(3)); System.out.println ("sentence.indexOf('g') " + sentence.indexOf('g') ); System.out.println ("sentence.indexOf('a', 10) " + sentence.indexOf('a', 10)); } sentence: Programming with Java sentence.charAt(3) g sentence.indexOf('g') 3 sentence.indexOf('a', 10) 18 Java Programming: Program Design Including Data Structures

Input/Output Input data Format output Output results Read from and write to files Java Programming: Program Design Including Data Structures

Formatting Output with printf printf syntax (standard output device) System.out.printf(formatString); or System.out.printf(formatString, argumentList); formatString specifies the format of the output argumentList is a list of arguments Constant values, variables, or expressions Arguments are separated with commas Java Programming: Program Design Including Data Structures

Formatting Output with printf (continued) Example using only the format string: System.out.printf("Hello there!"); Example using format string and argumentList: System.out.printf( "There are %.2f inches in %d centimeters. %n", centimeters / 2.54, centimeters); %.2f and %d are called format specifiers One-to-one correspondence between format specifiers and the arguments in argumentList Java Programming: Program Design Including Data Structures

Formatting Output with printf (continued) Example public class Demo01 { public static void main(String[] args) { // formating output using good-old printf int centimeters = 100; System.out.printf( "There are %.2f inches in %d centimeters. %n", centimeters / 2.54, centimeters); } _______________________________________________ Output: There are 39.37 inches in 100 centimeters. Java Programming: Program Design Including Data Structures

Formatting Output with printf (continued) The first format specifier, %.2f, is matched with the first argument, which is the expression centimeters / 2.54 The second format specifier, %d, is matched with the second argument, which is centimeters The format specifier %n positions the insertion point at the beginning of the next line (same as \n ) Java Programming: Program Design Including Data Structures

Formatting Output with printf (continued) A format specifier for general, character, and numeric types has the following syntax: %[argument_index$][flags][width][.precision]conversion Expressions in square brackets are optional Optional argument_index is a (decimal) integer that indicates argument position in the argument list Java Programming: Program Design Including Data Structures

Formatting Output with printf (continued) public class DemoJ01 { public static void main(String[] args) { // formating output using good-old C printf String fName = "Maria"; String lName = "Macarena"; System.out.printf( "The Queen of rumba is %1$-10s %2$s. Viva %3$10s%n", fName, lName, "Cuervo"); "The Queen of rumba is %1$10s %2$s. Viva %3$s%n", } The Queen of rumba is Maria Macarena. Viva Cuervo The Queen of rumba is Maria Macarena. Viva Cuervo Java Programming: Program Design Including Data Structures

Formatting Output with printf (continued) flags (optional) set of characters that modify the output format width (optional) is an integer that indicates the minimum number of characters to be written precision (optional) is an integer that restricts the number of characters conversion (required) is a character that indicates how the argument should be formatted Java Programming: Program Design Including Data Structures

Formatting Output with printf (continued) Java Programming: Program Design Including Data Structures

Formatting Output with printf (continued) flag meaning conversion types applicable '-' Result is left-aligned in the field. This flag is meaningless if no mandatory field width is specified. %d, %u, %o, %x, %X, %z[n], %Z[n], %f, %e, %E, %g, %G, %s, %c, %p '^' Result is centered in the field. This flag is meaningless if no mandatory field width is specified. '+' Non-negative values begin with a plus character ('+'). %d, %f ' ' Non-negative values begin with a space character (' '). This flag is only useful for signed conversion results (%d and %f). '#' Argument is represented in an "alternate form." This depends on the conversion type: %o Non-negative octal values are prepended with a zero ('0'). %x, %X Hexadecimal values are prepended with the prefix "0x" or "0X". %e, %E, %f The integer portion of the result always ends with a decimal point ('.'), even if the fractional portion is zero. %g, %G The fractional portion always appears, even if it is zero. %c If the character is special or unprintable, it is output in an escaped form. The output can be surrounded by single quotes to form a syntactically valid Java character literal. There is no alternate form for %s, %d, %u, %z[n], and %Z[n]. Java Programming: Program Design Including Data Structures

Formatting Output with printf (continued) Example: public class Demo03 { public static void main(String[] args) { System.out.printf ("Characters: %c %c \n", 'a', 65); System.out.printf ("Integrals: %d %d\n", 123, 999888777); System.out.printf ("Preceding with blanks: %10d \n", 2007); System.out.printf ("Preceding with zeros: %010d \n", 2007); System.out.printf ("Explicit signs: %+10d \n", 2007); System.out.printf ("Explicit signs: %+10d \n", -2007); System.out.printf ("Some different radixes: %d %x %X %o %#x %#o \n", 77, 77, 77, 77, 77, 77); System.out.printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416); System.out.printf ("%s \n", "A string"); } Characters: a A Integrals: 123 999888777 Preceding with blanks: 2007 Preceding with zeros: 0000002007 Explicit signs: +2007 Explicit signs: -2007 Some different radixes: 77 4d 4D 115 0x4d 0115 floats: 3.14 +3e+00 3.141600E+00 A string Java Programming: Program Design Including Data Structures

Parsing Numeric Strings A string consisting of only integers or decimal numbers is called a numeric string To convert a string consisting of an integer to a value of the type int, use: Integer.parseInt(strExpression) Integer.parseInt("6723") = 6723 Integer.parseInt("-823") = -823 Long.parseLong(strExpression) Long.parseLong("1234567890123456723") → 123456789012345 Java Programming: Program Design Including Data Structures

Parsing Numeric Strings (continued) To convert a string consisting of a decimal number to a value of the type float, use: Float.parseFloat(strExpression) Float.parseFloat("34.56") = 34.56 Float.parseFloat("-542.97") = -542.97 To convert a string consisting of a decimal number to a value of the type double, use: Double.parseDouble(strExpression) Double.parseDouble("345.78") = 345.78 Double.parseDouble("-782.873") = -782.873 Java Programming: Program Design Including Data Structures

Parsing Numeric Strings (continued) Integer, Float, and Double are classes designed to convert a numeric string into a number (not the same as: int, float, double) These classes are called wrapper classes parseInt: class Integer, converts a numeric integer string into a value of the type int parseFloat: class Float, converts a numeric decimal string into an equivalent value of the type float parseDouble: class Double, converts a numeric decimal string into an equivalent value of the type double Java Programming: Program Design Including Data Structures

Using Dialog Boxes for Input/Output Use a graphical user interface (GUI) class JOptionPane Contained in package javax.swing showInputDialog, showMessageDialog Syntax: str = JOptionPane.showInputDialog(strExpression) Program should end with System.exit(0); (to terminate the JVM) Java Programming: Program Design Including Data Structures

Using Dialog Boxes for Input/Output import javax.swing.*; public class UsingDialogBoxes1 { public static void main(String[] argv) String str; int age; str = JOptionPane.showInputDialog("Enter your name"); System.out.println ("You said " + str); str = JOptionPane.showInputDialog("Enter your age"); age = Integer.parseInt(str); System.out.println ("You said " + age); } You said maria macarena You said 27 Java Programming: Program Design Including Data Structures

Parameters for the Method showMessageDialog Java Programming: Program Design Including Data Structures

JOptionPane Options for the Parameter messageType Java Programming: Program Design Including Data Structures

JOptionPane Example Java Programming: Program Design Including Data Structures

Formatting the Output Using the String Method format Example 3-13 double x = 15.674; double y = 235.73; double z = 9525.9864; int num = 83; String str; Java Programming: Program Design Including Data Structures

Formatting the Output Using the String Method format Example public class DemoJ01 { public static void main(String[] args) { double payRate = 7.789; String myResult; System.out.println("The result is " + payRate); myResult = String.format("The result is %.2f", payRate); System.out.println(myResult); } The result is 7.79 The result is 7.789 Java Programming: Program Design Including Data Structures

File Input/Output File: area in secondary storage that holds info You can initialize a Scanner object to input sources other than the standard input device by passing an appropriate argument in place of the object System.in Use class FileReader Java Programming: Program Design Including Data Structures

File Input/Output (continued) Suppose that the input data is stored in a file, say prog.dat, and this file is on floppy disk A Create a Scanner object inFile and initialize it to the file a:\prog.dat: Scanner inFile = new Scanner(new fileReader("a:\\prog.dat")); Use inFile to input data from prog.dat (Similar to using console) Java Programming: Program Design Including Data Structures

File Input/Output (continued) Java file I/O process: Import necessary classes from the packages java.util and java.io into the program Create and associate appropriate objects with the input/output sources Use the appropriate methods associated with the variables created in Step 2 to input/output data Close the files Java Programming: Program Design Including Data Structures

File Input/Output (continued) Example 3-16 Suppose an input file, say employeeData.txt, consists of the following data: Emily Johnson 45 13.50 To acquire the data you place a Scanner object on the disk file Scanner inFile = new Scanner (new FileReader(“a:\\employeeData.txt")); Java Programming: Program Design Including Data Structures

File Input/Output (continued) Example 3-16 cont. import java.io.*; import java.util.*; public class Demo04 { public static void main (String[] argv) throws IOException, FileNotFoundException Scanner inFile = new Scanner (new FileReader("c:\\employeeData.txt")); String firstName, lastName; double hoursWorked, payRate, wages; //read single data row (later will learn how to use hasNext() for multiple records) firstName = inFile.next(); lastName = inFile.next(); hoursWorked = inFile.nextDouble(); payRate = inFile.nextDouble(); wages = hoursWorked * payRate; System.out.println ("ECHO. Here is what I read from the disk file\n"); System.out.printf("Name: %s %s Hours: %.2f Rate: %.2f Wages: %.2f", firstName, lastName, hoursWorked, payRate, wages); inFile.close(); //close the input file } ECHO. Here is what I read from the disk file Name: Emily Johnson Hours: 45.00 Rate: 13.50 Wages: 607.50 Java Programming: Program Design Including Data Structures

Storing (Writing) Output in a File To store output in a file, use the class PrintWriter Declare a PrintWriter variable and associate this variable with the destination Suppose the output is to be stored in the file prog.out on floppy disk A Java Programming: Program Design Including Data Structures

Storing (Writing) Output in a File (continued) Consider the following statement: PrintWriter outFile = new PrintWriter("a:\\prog.out"); Creates PrintWriter object outFile and associates it with prog.out on floppy disk A Use print, println, printf, and flush with outFile just as with the object System.out Java Programming: Program Design Including Data Structures

Storing (Writing) Output in a File (continued) The statement: outFile.println("The paycheck is: $" + pay); stores the output in prog.out Close input and output files using method close inFile.close(); outFile.close(); Closing the output file ensures that the buffer holding the output will be emptied Java Programming: Program Design Including Data Structures

Storing (Writing) Output in a File (continued) Example import java.io.*; public class Demo05 { public static void main (String[] argv) throws IOException, FileNotFoundException PrintWriter outFile = new PrintWriter("c:\\prog.out"); //PrintWriter outFile = new PrintWriter(System.out); outFile.printf("%s %d %.2f", "Hermione Wrangler", 17, 1234.567); outFile.close(); } Hermione Wrangler 17 1234.57 Java Programming: Program Design Including Data Structures

Storing (Writing) Output in a File (continued) Various errors can arise during program execution: Division by zero Inputting a letter for a number In such cases, we say that an exception has occurred If an exception occurs in a method, then the method should either handle the exception or throw it for the calling environment to handle Java Programming: Program Design Including Data Structures

Storing (Writing) Output in a File (continued) If an input file does not exist, the program throws a FileNotFoundException If an output file cannot be created or accessed, the program throws a FileNotFoundException Because we do not need the method main to handle the FileNotFoundException exception, include a command in the heading of main to throw the FileNotFoundException exception Java Programming: Program Design Including Data Structures

Skeleton of I/O Program Java Programming: Program Design Including Data Structures

Programming Example: Movie Ticket Sale and Donation to Charity Input: Movie name, ticket prices, etc. Output: Java Programming: Program Design Including Data Structures

Programming Example: Movie Ticket Sale and Donation to Charity (continued) Import appropriate packages Get inputs from user using JOptionPane.showInputDialog Perform appropriate calculations Display output using JOptionPane.showMessageDialog Java Programming: Program Design Including Data Structures

Programming Example: Student Grade Input: File containing student’s first name, last name, five test scores Output: File containing student’s first name, last name, five test scores, average of five test scores Java Programming: Program Design Including Data Structures

Programming Example: Student Grade (continued) Import appropriate packages Get input from file using the classes Scanner and FileReader Read and calculate the average of test scores Write to output file using the class PrintWriter Close files Java Programming: Program Design Including Data Structures

Chapter Summary Primitive type variables store data into their memory space Reference variables store the address of the object containing the data An object is an instance of a class Operator new is used to instantiate an object Garbage collection reclaims unused memory Java Programming: Program Design Including Data Structures

Chapter Summary (continued) To use a predefined method, you must know its name and the class and package it belongs to The dot (.) operator accesses a method in a class Methods of the class String are used to manipulate input and output data Dialog boxes can accept data and show results Data can be read from and written to files Data can be formatted using the String method format Java Programming: Program Design Including Data Structures