Download presentation
Presentation is loading. Please wait.
Published byTiffany Gilmore Modified over 6 years ago
1
Chapter 3: Introduction to Objects and Input/Output
Java Programming: Program Design Including Data Structures
2
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
3
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
4
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
5
Object and Reference Variables (continued)
String str; str = "Hello there!"; Java Programming: Program Design Including Data Structures
6
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
7
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
8
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
9
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
10
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
11
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
12
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
13
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
14
Commonly Used String Methods
sentence = “Programming with Java” Java Programming: Program Design Including Data Structures
15
Commonly Used String Methods (continued)
sentence = “Programming with Java” Java Programming: Program Design Including Data Structures
16
Commonly Used String Methods (continued)
sentence = “Programming with Java” Java Programming: Program Design Including Data Structures
17
Commonly Used String Methods (continued)
sentence = “Programming with Java” Java Programming: Program Design Including Data Structures
18
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
19
Input/Output Input data Format output Output results
Read from and write to files Java Programming: Program Design Including Data Structures
20
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
21
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
22
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 inches in 100 centimeters. Java Programming: Program Design Including Data Structures
23
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
24
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
25
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
26
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
27
Formatting Output with printf (continued)
Java Programming: Program Design Including Data Structures
28
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
29
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, ); 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, , ); System.out.printf ("%s \n", "A string"); } Characters: a A Integrals: Preceding with blanks: Preceding with zeros: Explicit signs: Explicit signs: Some different radixes: 77 4d 4D 115 0x4d 0115 floats: e E+00 A string Java Programming: Program Design Including Data Structures
30
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(" ") → Java Programming: Program Design Including Data Structures
31
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(" ") = To convert a string consisting of a decimal number to a value of the type double, use: Double.parseDouble(strExpression) Double.parseDouble("345.78") = Double.parseDouble(" ") = Java Programming: Program Design Including Data Structures
32
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
33
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
34
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
35
Parameters for the Method showMessageDialog
Java Programming: Program Design Including Data Structures
36
JOptionPane Options for the Parameter messageType
Java Programming: Program Design Including Data Structures
37
JOptionPane Example Java Programming: Program Design Including Data Structures
38
Formatting the Output Using the String Method format
Example 3-13 double x = ; double y = ; double z = ; int num = 83; String str; Java Programming: Program Design Including Data Structures
39
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
40
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
41
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
42
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
43
File Input/Output (continued)
Example 3-16 Suppose an input file, say employeeData.txt, consists of the following data: Emily Johnson 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
44
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: Rate: Wages: Java Programming: Program Design Including Data Structures
45
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
46
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
47
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
48
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, ); outFile.close(); } Hermione Wrangler Java Programming: Program Design Including Data Structures
49
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
50
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
51
Skeleton of I/O Program
Java Programming: Program Design Including Data Structures
52
Programming Example: Movie Ticket Sale and Donation to Charity
Input: Movie name, ticket prices, etc. Output: Java Programming: Program Design Including Data Structures
53
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
54
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
55
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
56
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
57
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.