Building Java Programs Chapter 1 Introduction to Java

Building Java Programs Chapter 1: Introduction to Java Programming Copyright 2006 by Pearson Education 1

Syntax errors n syntax error or compiler error: A problem in the structure of a program that causes the compiler to fail. n 1 2 3 4 5 If you type your Java program incorrectly, you may violate Java's syntax and cause a syntax error. public class Hello { pooblic static void main(String[] args) { System. owt. println("Hello, world!")_ } } compiler output: Hello. java: 2: <identifier> expected pooblic static void main(String[] args) { ^ Hello. java: 5: '; ' expected } ^ 2 errors Copyright 2006 by Pearson Education 2

Fixing syntax errors n Error messages do not always help us understand what is wrong: Hello. java: 2: <identifier> expected pooblic static void main(String[] args) { ^ n n The compiler does tell us the line number on which it found the error. . . n 1 2 3 4 5 6 We'd have preferred a friendly message such as, "You misspelled public" But it is not always the true source of the problem. public class Missing. Semicolon { public static void main(String[] args) { System. out. println("A rose by any other name") System. out. println("would smell as sweet"); } } Missing. Semicolon. java: 4: '; ' expected System. out. println("would smell as sweet"); ^ Copyright 2006 by Pearson Education 3

Syntax Errors. To Try these errors: n Misspell output n Remove a semi-colon n Remove a curly brace Notice the error messages Copyright 2006 by Pearson Education

Questions n What is the output of each of the following println statements? System. out. println("tatbtc"); System. out. println("\\"); System. out. println("'"); System. out. println("""""); System. out. println("C: ninthe downward spiral"); n Write a println statement to produce the following line of output: / // \ /// \ Copyright 2006 by Pearson Education 5

Answers n Output of each println statement: a \ ' """ C: in n b c he downward spiral println statement to produce the line of output: System. out. println("/ \ // \\ /// \\\"); Copyright 2006 by Pearson Education 6

Questions n What println statements will generate the following output? This program prints a quote from the Gettysburg Address. "Four score and seven years ago, our 'fore fathers' brought forth on this continent a new nation. " n What println statements will generate the following output? A "quoted" String is 'much' better if you learn the rules of "escape sequences. " Also, "" represents an empty String. Don't forget: use " instead of " ! '' is not the same as " Copyright 2006 by Pearson Education 7

Answers n println statements to generate the output: System. out. println("This program prints a"); System. out. println("quote from the Gettysburg Address. "); System. out. println(""Four score and seven years ago, "); System. out. println("our 'fore fathers' brought forth on"); System. out. println("this continent a new nation. ""); n println statements to generate the output: System. out. println("A "quoted" String is"); System. out. println("'much' better if you learn"); System. out. println("the rules of "escape sequences. ""); System. out. println("Also, "" represents an empty String. "); System. out. println("Don't forget: use \" instead of " !"); System. out. println("'' is not the same as ""); Copyright 2006 by Pearson Education 8

Procedural decomposition using static methods reading: 1. 4 Copyright 2006 by Pearson Education 9

Algorithms n n algorithm: A list of steps for solving a problem. How does one bake sugar cookies? (what is the "bake sugar cookies" algorithm? ) n n n Mix the dry ingredients. Cream the butter and sugar. Beat in the eggs. Stir in the dry ingredients. Set the oven for the appropriate temperature. Set the timer. Place the cookies into the oven. Allow the cookies to bake. Mix the ingredients for the frosting. Spread frosting and sprinkles onto the cookies. . Copyright 2006 by Pearson Education 10

Structured algorithms n structured algorithm: One broken down into cohesive tasks. n A structured algorithm for baking sugar cookies: 1. Make the cookie batter. n Mix the dry ingredients. n Cream the butter and sugar. n Beat in the eggs. n Stir in the dry ingredients. 2. Bake the cookies. n Set the oven for the appropriate temperature. n Set the timer. n Place the cookies into the oven. n Allow the cookies to bake. 3. Add frosting and sprinkles. n Mix the ingredients for the frosting. n Spread frosting and sprinkles onto the cookies. . Copyright 2006 by Pearson Education 11

Static method questions n I I I Write a program that prints the following output to the console. Use static methods as appropriate. do not like my email spam, do not like them, Sam I am! do not like them on my screen, do not like them to be seen. do not like my email spam, do not like them, Sam I am! Write a program that prints the following output to the console. Use static methods as appropriate. Lollipop, lollipop Oh, lolli n Lollipop, lollipop Oh, lolli Call my baby lollipop Copyright 2006 by Pearson Education 12

Identifiers, keywords, and comments reading: 1. 2 Copyright 2006 by Pearson Education 13

Identifiers n identifier: A name given to a piece of data, method, etc. n n Identifiers allow us to refer to an item later in the program. Identifiers give names to: n n classes methods variables, constants (seen in Ch. 2) Conventions for naming in Java: n n n classes: capitalize each word (Class. Name) methods: capitalize each word after the first (method. Name) (variable names follow the same convention) constants: all caps, words separated by _ (CONSTANT_NAME) Copyright 2006 by Pearson Education 14

Details about identifiers n Java identifiers: n n first character must a letter or _ or $ following characters can be any of those or a number identifiers are case-sensitive (name is different from Name) Example Java identifiers: n n legal: susan The. Cure illegal: me+u side-swipe jim's n second_place ANSWER_IS_42 _my. Name $variable 49 er hi there 2%milk question? ph. d suzy@yahoo. com can you explain why each of the above identifiers is not legal? Copyright 2006 by Pearson Education 15

Keywords n n keyword: An identifier that you cannot use because it already has a reserved meaning in the Java language. Complete list of Java keywords: abstract boolean break byte case catch char class const continue n default do double else extends finally float for goto if implements import instanceof interface long native new package private protected public return short static strictfp super switch synchronized this throws transient try void volatile while You may not use char or while for the name of a class or method; Java reserves those to mean other things. n You could use CHAR or While, because Java is case-sensitive. However, this could be confusing and is not recommended. Copyright 2006 by Pearson Education 16

Are These Valid? n n n n 1 avar one. AVar default one+three one 3 one_three a. Var a Var Copyright 2006 by Pearson Education 17

Java Story Assignment: http: //home. adelphi. edu/~pe 16132/csc 171/assignments/ first. Java. Assignment. htm n Prep for Homework: http: //home. adelphi. edu/~pe 16132/csc 171/assignments/ name. Java. htm Copyright 2006 by Pearson Education 18

Drawing complex figures using static methods reading: 1. 4 - 1. 5 Copyright 2006 by Pearson Education 19

Static methods question n Write a program to print the following figures. Use static methods for structure and to reduce redundancy. ______ / / WE WILL ONLY DO THIS PART IF TIME ALLOWS ______/ / ______/ +----+ ______ / / | | / STOP ______/ ______ / +----+ Copyright 2006 by Pearson Education 20

Problem-solving methodology n Some steps we can use to print complex figures: ______ / / ______/ First version of program (unstructured): n / ______/ +----+ n ______ / / | | / STOP n Create an empty program with a skeletal header and main method. Copy the expected output into it, surrounding each line with System. out. println syntax. Run our first version and verify that it produces the correct output. ______/ ______ / +----+ Copyright 2006 by Pearson Education 21

Program, version 1 // Author: Suzy Student // This program prints several assorted figures. // public class Figures 1 { public static void main(String[] args) { System. out. println(" ______"); System. out. println(" / \"); System. out. println("\ /"); System. out. println(" \______/"); System. out. println("+----+"); System. out. println(" ______"); System. out. println(" / \"); System. out. println("| STOP |"); System. out. println("\ /"); System. out. println(" \______/"); System. out. println(" ______"); System. out. println(" / \"); System. out. println("+----+"); } } Copyright 2006 by Pearson Education 22

Problem-solving 2 ______ / / Second version of program (structured with redundancy): ______/ / n ______/ +----+ n Identify the structure of the output. Divide the main method into several static methods based on this structure. ______ / / | | / STOP ______/ ______ / +----+ Copyright 2006 by Pearson Education 23

Problem-solving 2 answer ______ / / ______/ +----+ The structure of the output: n initial "egg" figure n second "teacup" figure n third "stop sign" figure n fourth "hat" figure ______ / / | | / STOP ______/ ______ / +----+ This structure can be represented by methods: n draw. Egg n draw. Tea. Cup n draw. Stop. Sign n draw. Hat Copyright 2006 by Pearson Education 24

Program, version 2 // Author: Suzy Student // Prints several assorted figures, with methods for structure. // public class Figures 2 { public static void main(String[] args) { draw. Egg(); draw. Tea. Cup(); draw. Stop. Sign(); draw. Hat(); } // Draws a figure that vaguely resembles an egg. public static void draw. Egg() { System. out. println(" ______"); System. out. println(" / \"); System. out. println("\ /"); System. out. println(" \______/"); System. out. println(); } // Draws a figure that vaguely resembles a teacup. public static void draw. Tea. Cup() { System. out. println("\ /"); System. out. println(" \______/"); System. out. println("+----+"); System. out. println(); }. . . Copyright 2006 by Pearson Education 25

Program, version 2, cont'd. . // Draws a figure that vaguely resembles a stop sign. public static void draw. Stop. Sign() { System. out. println(" ______"); System. out. println(" / \"); System. out. println("| STOP |"); System. out. println("\ /"); System. out. println(" \______/"); System. out. println(); } } // Draws a figure that vaguely resembles a hat. public static void draw. Hat() { System. out. println(" ______"); System. out. println(" / \"); System. out. println("+----+"); } Copyright 2006 by Pearson Education 26

Problem-solving 3 ______ / / Third version of program (structured without redundancy): ______/ / n ______/ +----+ Identify any redundancy in the output, and further divide the program into static methods to eliminate as much redundancy as possible. ______ / / | | / STOP n Add comments to the program to improve its readability. ______/ ______ / +----+ Copyright 2006 by Pearson Education 27

Problem-solving 3 answer ______ / / ______/ The redundancy in the output: n / n ______/ +----+ n top half of egg: reused on stop sign, hat bottom half of egg: reused on teacup, stop sign divider line: used on teacup, hat n ______ / a single line, so making it a method is optional / | | / STOP ______/ ______ / This redundancy can be fixed by methods: n draw. Egg. Top n draw. Egg. Bottom n draw. Line (optional) / +----+ Copyright 2006 by Pearson Education 28

Program, version 3 // Author: Suzy Student // Prints several figures, with methods for structure and redundancy. // public class Figures 3 { public static void main(String[] args) { draw. Egg(); draw. Tea. Cup(); draw. Stop. Sign(); draw. Hat(); } // draws redundant part that looks like the top of an egg public static void draw. Egg. Top() { System. out. println(" ______"); System. out. println(" / \"); System. out. println("/ \"); } // draws redundant part that looks like the bottom of an egg public static void draw. Egg. Bottom() { System. out. println("\ /"); System. out. println(" \______/"); }. . . Copyright 2006 by Pearson Education 29

Program, version 3, cont'd. } . . . // Draws a figure that vaguely resembles public static void draw. Egg() { draw. Egg. Top(); draw. Egg. Bottom(); System. out. println(); } // Draws a figure that vaguely resembles public static void draw. Tea. Cup() { draw. Egg. Bottom(); System. out. println("+----+"); System. out. println(); } // Draws a figure that vaguely resembles public static void draw. Stop. Sign() { draw. Egg. Top(); System. out. println("| STOP |"); draw. Egg. Bottom(); System. out. println(); } // Draws a figure that vaguely resembles public static void draw. Hat() { draw. Egg. Top(); System. out. println("+----+"); } Copyright 2006 by Pearson Education an egg. a teacup. a stop sign. a hat. 30

Another example n Write a program to print letters spelling "banana". Use static methods for structure and to reduce redundancy. BBBBB B B BBBBB AAAA A A AAAAAA A A N N NNN N N AAAA A A AAAAAA A A Copyright 2006 by Pearson Education 31
- Slides: 31