©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 2 - 1 Chapter 2 Getting Started with Java Animated Version.

Slides:



Advertisements
Similar presentations
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 2 Getting Started with Java.
Advertisements

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 2 Getting Started with Java Animated Version.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Ch2: Getting Started with Java - Objectives After.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 2 Getting Started with Java Program development.
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 2 Getting Started with Java Structure of.
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
Chapter 3 Using Classes and Objects. Creating Objects A variable holds either a primitive type or a reference to an object A class name can be used as.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 2 Getting Started with Java Structure of.
Getting Started with Java
©2004 Brooks/Cole Chapter 1: Getting Started Sections Covered: 1.1Introduction to Programming 1.2Constructing a Java Program 1.3The print() and println()
Aalborg Media Lab 21-Jun-15 Software Design Lecture 1 “ Introduction to Java and OOP”
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 2: Getting Started with Java *Components.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 2 Getting Started with Java.
Chapter Chapter 2 Getting Started with Java.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Chapter 2 Getting Started with Java Part B. Topics Components of a Java Program –classes –methods –comments –import statements Declaring and creating.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: IO *Standard Output *Formatting Decimal.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Software Engineering Software Development Process.
1 Interactive Applications (CLI) Interactive Applications Command Line Interfaces Project 1: Calculating BMI Example: Factoring the Solution Reading for.
Java Programming, 2E Introductory Concepts and Techniques Chapter 2 Creating a Java Application and Applet.
CS1101: Programming Methodology
Java Programming, 3e Concepts and Techniques Chapter 2 - Part 2 Creating a Java Application and Applet.
Simple Programs from Chapter 2 Putting the Building Blocks All Together (corresponds with Chapter 2)
Getting Started with Java Recitation – 1/23/2009 CS 180 Department of Computer Science, Purdue University.
The Java Programming Language
1 The String Class Every character string is an object in Java, defined by the String class Every string literal, delimited by double quotation marks,
Computer Programming 2 Lab(1) I.Fatimah Alzahrani.
CHAPTER 3 GC Java Fundamentals. 2 BASICS OF JAVA ENVIRONMENT  The environment  The language  Java applications programming Interface API  Various.
CS1101X: Programming Methodology Recitation 1 Java Basics Numerical Data.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
 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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Sample Slides - 1 Sample Animated Slides for Wu, Intro to OOP.
© 2004 Pearson Addison-Wesley. All rights reserved ComS 207: Programming I Instructor: Alexander Stoytchev
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
Chapter 2 Getting Started with Java. Objectives After you have read and studied this chapter, you should be able to Identify the basic components of Java.
 2005 Pearson Education, Inc. All rights reserved. 1 A class A class is the blueprint from which objects are generated. In other words, if we have six.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
1 Training Lecture 1. 2 Primitive Data Declaration and Assignments Code State of Memory int firstNumber, secondNumber; firstNumber = 234; secondNumber.
Using Classes and Objects Chapters 3 Creating Objects – Section 3.1 The String Class – Section 3.2 The Scanner Class – Section 2.6 Instructor: Scott Kristjanson.
Chapter 2: Data and Expressions String and String Concatenation Escape Sequences Variables Primitive Date Types Expressions Interactive Programs.
CSE 1201 Object Oriented Programming Using Classes and Objects.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Getting Started with Java: Object declaration and creation Primitive.
Creating a Java Application and Applet
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 2 Getting Started with Java Animated Version.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
Strings and I/O. Lotsa String Stuff… There are close to 50 methods defined in the String class. We will introduce several of them here: charAt, substring,
1 Data and Expressions Chapter 2 In PowerPoint, click on the speaker icon then the “play” button to hear audio narration.
بسم الله الرحمن الرحيم CPCS203: Programming II. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display., Modifications by Dr.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Scanner Review Java Foundations: Introduction to Programming and Data Structures.
Interactive Programs Programs that get input from the user 1 In PowerPoint, click on the speaker icon then click the "Play" button to hear the narration.
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.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Lecture 4 – Scanner & Style
Variables in Java A variable holds either
Intro to OOP with Java, C. Thomas Wu
Intro to OOP with Java, C. Thomas Wu Getting Started with Java
2.5 Another Java Application: Adding Integers
CSC 1051 – Data Structures and Algorithms I
Chapter 2 - Introduction to Java Applications
Introduction to Java Programming
Getting Started with Java
Computer Programming-1 CSC 111
Instructor: Alexander Stoytchev
Presentation transcript:

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 2 Getting Started with Java Animated Version

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Objectives After you have read and studied this chapter, you should be able to Identify the basic components of Java programs Write simple Java programs Describe the difference between object declaration and creation Describe the process of creating and running Java programs Use the Date, SimpleDateFormat, String, and JOptionPane standard classes Develop Java programs, using the incremental development approach

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter The First Java Program The fundamental OOP concept illustrated by the program: An object-oriented program uses objects. This program displays a window on the screen. The size of the window is set to 300 pixels wide and 200 pixels high. Its title is set to My First Java Program.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Program Ch2Sample1 import javax.swing.*; class Ch2Sample1 { public static void main(String[ ] args) { JFramemyWindow; myWindow = new JFrame( ); myWindow.setSize(300, 200); myWindow.setTitle(“My First Java Program”); myWindow.setVisible(true); } Declare a name Create an object Use an object

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Program Diagram for Ch2Sample1 myWindow : JFrame Ch2Sample1 setSize(300, 200) setTitle(“My First Java Program”) setVisible(true)

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Dependency Relationship myWindow : JFrame Ch2Sample1 Instead of drawing all messages, we summarize it by showing only the dependency relationship. The diagram shows that Ch2Sample1 “depends” on the service provided by myWindow.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter More Examples Object Declaration JFrame myWindow; Accountcustomer; Studentjan, jim, jon; Vehiclecar1, car2; Object Name One object is declared here. Object Name One object is declared here. Class Name This class must be defined before this declaration can be stated. Class Name This class must be defined before this declaration can be stated.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Object Creation myWindow = new JFrame ( ) ; More Examples customer = new Customer( ); jon= new Student(“John Java”); car1= new Vehicle( ); Object Name Name of the object we are creating here. Object Name Name of the object we are creating here. Class Name An instance of this class is created. Class Name An instance of this class is created. Argument No arguments are used here. Argument No arguments are used here.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Declaration vs. Creation Customer customer; customer = new Customer( ); Customer customer; customer = new Customer( ); 1. The identifier customer is declared and space is allocated in memory. 2. A Customer object is created and the identifier customer is set to refer to it. 1 2 customer 1 : Customer 2

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter State-of-Memory vs. Program customer : Customer State-of-Memory Notation customer : Customer Program Diagram Notation

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Name vs. Objects Customer customer; customer = new Customer( ); Customer customer; customer customer = new Customer( ); : Customer Created with the first new. Created with the second new. Reference to the first Customer object is lost.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Sending a Message myWindow. setVisible ( true ) ; More Examples account.deposit( ); student.setName(“john”); car1.startEngine( ); Object Name Name of the object to which we are sending a message. Object Name Name of the object to which we are sending a message. Method Name The name of the message we are sending. Method Name The name of the message we are sending. Argument The argument we are passing with the message. Argument The argument we are passing with the message.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter JFrame myWindow; myWindow = new JFrame( ); myWindow.setSize(300, 200); myWindow.setTitle (“My First Java Program”); myWindow.setVisible(true); Execution Flow myWindow.setSize(300, 200); Jframe myWindow; myWindow myWindow.setVisible(true); State-of-Memory Diagram : JFrame width height title visible 200 My First Java … 300 true myWindow = new JFrame( ); myWindow.setTitle (“My First Java Program”); The diagram shows only four of the many data members of a JFrame object. Program Code

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Program Components A Java program is composed of –comments, –import statements, and –class declarations.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter /* Chapter 2 Sample Program: Displaying a Window File: Ch2Sample2.java */ import javax.swing.*; class Ch2Sample1 { public static void main(String[ ] args) { JFramemyWindow; myWindow = new JFrame( ); myWindow.setSize(300, 200); myWindow.setTitle(“My First Java Program”); myWindow.setVisible(true); } Program Component: Comment Comment

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Matching Comment Markers /* This is a comment on one line */ /* Comment number 1 */ /* Comment number 2 */ /* This is a comment */ Error: No matching beginning marker. These are part of the comment.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Three Types of Comments /* This is a comment with three lines of text. */ Multiline Comment Single line Comments // This is a comment // This is another comment // This is a third comment /** * This class provides basic clock functions. In addition * to reading the current time and today ’ s date, you can * use this class for stopwatch functions. */ javadoc Comments

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Import Statement /* Chapter 2 Sample Program: Displaying a Window File: Ch2Sample2.java */ import javax.swing.*; class Ch2Sample1 { public static void main(String[ ] args) { JFramemyWindow; myWindow = new JFrame( ); myWindow.setSize(300, 200); myWindow.setTitle(“My First Java Program”); myWindow.setVisible(true); } Import Statement

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Import Statement Syntax and Semantics. ; e.g. dorm. Resident; More Examples import javax.swing.JFrame; import java.util.*; import com.drcaffeine.simplegui.*; Class Name The name of the class we want to import. Use asterisks to import all classes. Class Name The name of the class we want to import. Use asterisks to import all classes. Package Name Name of the package that contains the classes we want to use. Package Name Name of the package that contains the classes we want to use.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Packages The classes of the Java standard class library are organized into packages Some of the packages in the standard class library are: Package java.lang java.applet java.awt javax.swing java.net java.util javax.xml.parsers Purpose General support (System, String) outomatic Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities Network communication Utilities XML document processing

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Class Declaration /* Chapter 2 Sample Program: Displaying a Window File: Ch2Sample2.java */ import javax.swing.*; class Ch2Sample1 { public static void main(String[ ] args) { JFramemyWindow; myWindow = new JFrame( ); myWindow.setSize(300, 200); myWindow.setTitle(“My First Java Program”); myWindow.setVisible(true); } Class Declaration

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Method Declaration /* Chapter 2 Sample Program: Displaying a Window File: Ch2Sample2.java */ import javax.swing.*; class Ch2Sample1 { public static void main(String[ ] args) { JFramemyWindow; myWindow = new JFrame( ); myWindow.setSize(300, 200); myWindow.setTitle(“My First Java Program”); myWindow.setVisible(true); } Method Declaration

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Method Declaration Elements public static void main( String[ ] args ){ JFramemyWindow; myWindow = new JFrame( ); myWindow.setSize(300, 200); myWindow.setTitle(“My First Java Program”); myWindow.setVisible(true); } Method Body Modifier Return Type Method Name Parameter

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Template for Simple Java Programs /* Chapter 2 Sample Program: Displaying a Window File: Ch2Sample2.java */ import javax.swing.*; class Ch2Sample1 { public static void main(String[ ] args) { JFramemyWindow; myWindow = new JFrame( ); myWindow.setSize(300, 200); myWindow.setTitle(“My First Java Program”); myWindow.setVisible(true); } Import Statements Class Name Comment Method Body

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Edit-Compile-Run Cycle Step1: you type the program using an editor and save the program to a file Step 3 :Another software tool, called an interpreter, translates bytecode into machine language and executes it Step2 : Compile the source file. The compiler check the syntax error, then if the compilation is successful, then bytecode file is created. Java Compiler Java bytecode Java bytecode is not the machine language for any traditional CPU Bytecode Interpreter Machine Code myProgram.exe Java source code JCreator editor

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Errors A program can have three types of errors The compiler will find syntax errors and other basic problems (compile-time errors) –If compile-time errors exist, an executable version of the program is not created A problem can occur during program execution, such as trying to divide by zero, which causes a program to terminate abnormally (run-time “ execution” errors) A program may run, but produce incorrect results, perhaps using an incorrect formula (logical errors)

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Why Use Standard Classes When there are existing objects that satisfy our needs, use them. Learning how to use standard Java classes is the first step toward mastering OOP. Before we can learn how to define our own classes, we need to learn how to use existing classes We will introduce four standard classes here: –JOptionPane - Scanner & System.out –String - Math & Random –Date –SimpleDateFormat.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Standard Output The program needs to display results or Strings Java uses Console Window called “ Stander Output Window “ to display via System.out The System.out object represents a destination (the monitor screen) to which we can send output System.out.println (" A Hadith by Prophet Mohammed:"); object method name information provided to the method (parameters)

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Standard Output The System.out object provides another service as well The print method is similar to the println method, except that it does not advance to the next line Therefore anything printed after a print statement will appear on the same line System.out.print ("Three... "); System.out.print ("Two... "); System.out.print ("One... "); System.out.print ("Zero... "); System.out.println ("Liftoff!"); // appears on first output line System.out.println ("Houston, we have a problem.") Three... Two... One... Zero... Liftoff! Houston, we have a problem.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Escape Sequences Some Java escape sequences: Escape Sequence \b \t \n \r \" \' \\ Meaning backspace tab newline carriage return double quote single quote backslash

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter String The textual values passed to the print method are instances of the String class. A sequence of characters separated by double quotes is a String constant. There are close to 50 methods defined in the String class. We will introduce some of them here: substring, length, indexOf, and others. We will also introduce a string operation called concatenation.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter String is an Object 1. The identifier name is declared and space is allocated in memory. 2. A String object is created and the identifier name is set to refer to it. 1 2 name 1 String name; name = new String(“Jon Java”); String name; name = new String(“Jon Java”); 2 : String Jon Java

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter String Indexing The position, or index, of the first character is 0.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter String Methods Once a String object has been created, neither its value nor its length can be changed Thus we say that an object of the String class is immutable However, several methods of the String class return new String objects that are modified versions of the original char charAt( int index); String replace (char oldChar, char newChar); int compareTo(String str); String substring (int offset, int endIndex); String concat (String str); String toLowerCase(); boolean equals(String str); String toUpperCase(); boolean equalsIgnoreCase(String str); int length();

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Definition: substring Assume str is a String object and properly initialized to a string. str.substring( i, j ) will return a new string by extracting characters of str from position i to j-1 where 0  i  length of str, 0  j  length of str, and i  j. If str is “programming”, then str.substring(3, 7) will create a new string whose value is “gram” because g is at position 3 and m is at position 6. The original string str remains unchanged.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Examples: substring String text = “Espresso”; text.substring(6,8) text.substring(0,8) text.substring(1,5) text.substring(3,3) text.substring(4,2) “so” “Espresso” “spre” error “”

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Definition: length Assume str is a String object and properly initialized to a string. str.length( ) will return the number of characters in str. If str is “programming”, then str.length( ) will return 11 because there are 11 characters in it. The original string str remains unchanged.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Examples: length String str1, str2, str3, str4; str1 = “Hello” ; str2 = “Java” ; str3 = “” ; //empty string str4 = “ “ ; //one space str1.length( ) str2.length( ) str3.length( ) str4.length( )

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Definition: indexOf Assume str and substr are String objects and properly initialized. str.indexOf( substr ) will return the first position substr occurs in str. If str is “programming” and substr is “gram”, then str.indexOf(substr ) will return 3 because the position of the first character of substr in str is 3. If substr does not occur in str, then –1 is returned. The search is case-sensitive.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Examples: indexOf String str; str = “I Love Java and Java loves me.” ; str.indexOf( “J” ) str2.indexOf( “love” ) str3. indexOf( “ove” ) str4. indexOf( “Me” )

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Definition: concatenation Assume str1 and str2 are String objects and properly initialized. str1 + str2 will return a new string that is a concatenation of two strings. If str1 is “pro” and str2 is “gram”, then str1 + str2 will return “program”. Notice that this is an operator and not a method of the String class. The strings str1 and str2 remains the same.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Examples: concatenation String str1, str2; str1 = “Jon” ; str2 = “Java” ; str1 + str2 str1 + “ “ + str2 str2 + “, “ + str1 “Are you “ + str1 + “?” “JonJava” “Java, Jon” “Are you Jon?”

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter String Concatenation The + operator is also used for arithmetic addition The function that it performs depends on the type of the information on which it operates If both operands are strings, or if one is a string and one is a number, it performs string concatenation If both operands are numeric, it adds them The + operator is evaluated left to right, but parentheses can be used to force the order System.out.println ("24 and 45 concatenated: " ); System.out.println ("24 and 45 added: " + ( ));

Interactive Programs Programs generally need input on which to operate The Scanner class provides convenient methods for reading input values of various types A Scanner object can be set up to read input from various sources, including the user typing values on the keyboard –Scanner (InputStream source) –Scanner (File source) –Scanner (String source) Keyboard input is represented by the System.in object

Reading Input The following line creates a Scanner object that reads from the keyboard: Scanner scan = new Scanner (System.in); The new operator creates the Scanner object Once created, the Scanner object can be used to invoke various input methods, such as: answer = scan.nextLine(); The Scanner class is part of the java.util class library, and must be imported into a program to be used The nextLine method reads all of the input until the end of the line is found

Echo.java import java.util.Scanner; public class Echo { // // Reads a character string from the user and prints it. // public static void main (String[] args) { String message; Scanner scan = new Scanner (System.in); System.out.println ("Enter a line of text:"); message = scan.nextLine(); System.out.println ("You entered: \"" + message + "\""); } Enter a line of text: Set your laser printer on stun! You entered: " Set your laser printer on stun! "

Input Tokens white space is used to separate the elements (called tokens) of the input White space includes space characters, tabs, new line characters The next method of the Scanner class reads the next input token and returns it as a string Methods such as nextInt and nextDouble read data of particular types. –nextBoolean(), nextLong(), etc… –Boolean hasnext()

GasMileage.java import java.util.Scanner; public class GasMileage { // Calculates fuel efficiency based on values entered by the user. public static void main (String[] args) { int miles; double gallons, mpg; Scanner scan = new Scanner (System.in); System.out.print ("Enter the number of miles: "); miles = scan.nextInt(); System.out.print ("Enter the gallons of fuel used: "); gallons = scan.nextDouble(); mpg = miles / gallons; System.out.println ("Miles Per Gallon: " + mpg); } Enter the number of miles: 328 Enter the gallons of fuel used: 11.2 Miles Per Gallon:

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Date The Date class from the java.util package is used to represent a date. When a Date object is created, it is set to today (the current date set in the computer) The class has toString method that converts the internal format to a string. Date today; today = new Date( ); today.toString( ); “Fri Oct 31 10:05:18 PST 2003”

Chapter SimpleDateFormat The SimpleDateFormat class allows the Date information to be displayed with various format. Table 2.1 page 62 shows the formatting options. import java.text.*; Date today = new Date( ); SimpleDateFormat sdf1, sdf2; sdf1 = new SimpleDateFormat( “MM/dd/yy” ); sdf2 = new SimpleDateFormat( “MMMM dd, yyyy” ); sdf1.format(today); sdf2.format(today); “10/31/03” “October 31, 2003”

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter JOptionPane Using showMessageDialog of the JOptionPane class is a simple way to display a result of a computation to the user. JOptionPane.showMessageDialog(null, “I Love Java”); This dialog will appear at the center of the screen.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Displaying Multiple Lines of Text We can display multiple lines of text by separating lines with a new line marker \n. JOptionPane.showMessageDialog(null, “one\ntwo\nthree”);

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter JOptionPane for Input Using showInputDialog of the JOptionPane class is a simple way to input a string. String name; name = JOptionPane.showInputDialog (null, “What is your name?”); This dialog will appear at the center of the screen ready to accept an input.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Problem Statement Problem statement: Write a program that asks for the user’s first, middle, and last names and replies with their initials. Example: input: Andrew Lloyd Weber output: ALW

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Overall Plan Identify the major tasks the program has to perform. We need to know what to develop before we develop! Tasks: –Get the user’s first, middle, and last names –Extract the initials and create the monogram –Output the monogram

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Development Steps We will develop this program in two steps: 1.Start with the program template and add code to get input 2.Add code to compute and display the monogram

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Step 1 Design The program specification states “get the user’s name” but doesn’t say how. We will consider “how” in the Step 1 design We will use JOptionPane for input Input Style Choice #1 Input first, middle, and last names separately Input Style Choice #2 Input the full name at once We choose Style #2 because it is easier and quicker for the user to enter the information

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Step 1 Code /* Chapter 2 Sample Program: Displays the Monogram File: Step1/Ch2Monogram.java */ import javax.swing.*; class Ch2Monogram { public static void main (String[ ] args) { String name; name = JOptionPane.showInputDialog(null, "Enter your full name (first, middle, last):“); JOptionPane.showMessageDialog(null, name); }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Step 1 Test In the testing phase, we run the program and verify that –we can enter the name –the name we enter is displayed correctly

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Step 2 Design Our programming skills are limited, so we will make the following assumptions: –input string contains first, middle, and last names –first, middle, and last names are separated by single blank spaces Example John Quincy Adams(okay) John Kennedy(not okay) Harrison, William Henry (not okay)

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Step 2 Design (cont’d) Given the valid input, we can compute the monogram by –breaking the input name into first, middle, and last –extracting the first character from them –concatenating three first characters “Aaron Ben Cosner” “Aaron” “Ben Cosner” “Ben” “Cosner” “ABC”

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Step 2 Code /* Chapter 2 Sample Program: Displays the Monogram File: Step 2/Ch2MonogramStep2.java */ import javax.swing.*; class Ch2Monogram { public static void main (String[ ] args) { String name, first, middle, last, space, monogram; space = " “; //Input the full name name = JOptionPane.showInputDialog(null, "Enter your full name (first, middle, last):“ );

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Step 2 Code (cont’d) //Extract first, middle, and last names first = name.substring(0, name.indexOf(space)); name = name.substring(name.indexOf(space)+1, name.length()); middle = name.substring(0, name.indexOf(space)); last = name.substring(name.indexOf(space)+1, name.length()); //Compute the monogram monogram = first.substring(0, 1) + middle.substring(0, 1) + last.substring(0,1); //Output the result JOptionPane.showMessageDialog(null, "Your monogram is " + monogram); }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Step 2 Test In the testing phase, we run the program and verify that, for all valid input values, correct monograms are displayed. We run the program numerous times. Seeing one correct answer is not enough. We have to try out many different types of (valid) input values.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Program Review The work of a programmer is not done yet. Once the working program is developed, we perform a critical review and see if there are any missing features or possible improvements One suggestion –Improve the initial prompt so the user knows the valid input format requires single spaces between the first, middle, and last names