Download presentation
Presentation is loading. Please wait.
Published byRosa Lynch Modified over 8 years ago
1
2-1 Chapter 2 A Little Java Computing Fundamentals with Java Rick Mercer Franklin, Beedle & Associates, 2002 ISBN 1-887902-47-3 Presentation Copyright 2002, Rick Mercer Students who purchase and instructors who adopt Computing Fundamentals with Java by Rick Mercer are welcome to use this presentation as long as this copyright notice remains intact.
2
2-2 Chapter 2 A Little Java Outline distinguish the smallest parts of a program (tokens) Java's primitive types: int and double arithmetic expressions Input / Output
3
2-3 General Forms The book uses general forms to introduce parts of the Java programming language General forms provide information to create syntactically correct programs Anything in yellow boldface must be written exactly as shown ( class for example). Anything in italic represents something that must be supplied by the user. The italicized portions are defined elsewhere
4
2-4 General Form: A Java program (class) // comment: this must be in a file named class-name.java import TextReader; public class class-name { public static void main( String[] args ) public static void main( String[] args ) { variable declarations and initializations variable declarations and initializations class instance creations (constructing objects) class instance creations (constructing objects) messages and other operations such as assignments messages and other operations such as assignments }}
5
2-5 Example Java program // Read a number from the user it display its squared value // Read a number from the user it display its squared value import TextReader; // not necessary if file is in this folder import TextReader; // not necessary if file is in this folder public class ReadItAndSquareIt // class heading public class ReadItAndSquareIt // class heading{ public static void main( String[] args ) public static void main( String[] args ) { double x; // variable declaration double x; // variable declaration double result = 0.0; // initialization double result = 0.0; // initialization TextReader keyboard = new TextReader( ); // object TextReader keyboard = new TextReader( ); // object // 1. Input // 1. Input System.out.print( "Enter a number: " ); // message System.out.print( "Enter a number: " ); // message x = keyboard.readDouble( ); // message x = keyboard.readDouble( ); // message // 2. Process // 2. Process result = x * x; // assignment result = x * x; // assignment // 3. Output // 3. Output System.out.println( x + " squared = " + result ); System.out.println( x + " squared = " + result ); } // end main } // end main }// end class
6
2-6 Each program (class) has several parts imports to make classes available import java.io.*; import java.io.*; import java.text.DecimalFormat; import java.text.DecimalFormat; class heading filename: ReadItAndSquareIt.java public class ReadItAndSquareIt public class ReadItAndSquareIt A class has a collection of methods between { and } method heading The first programs only have this one public static void main( String[] args ) public static void main( String[] args ) variable declaration and initialization examples double x = 0.0; double x = 0.0; double result = 0.0; double result = 0.0;
7
2-7 Tokens: The atomic pieces of a Program A token is the smallest recognizable unit in a programming language. There are four types of tokens: special symbols identifiers keywords (reserved identifiers) literals
8
2-8 A "tokenized program" Each color represents a different token special symbol keyword identifier literal special symbol keyword identifier literal // Comment: The import is not really necessary // Comment: The import is not really necessary import java. lang. System ; import java. lang. System ; public class TokenizedProgram public class TokenizedProgram { public static void main( String[] args ) public static void main( String[] args ) { double aNumber = 0.0; double aNumber = 0.0; TextReader keyboard = new TextReader( ); TextReader keyboard = new TextReader( ); System.out.print( "Enter a number: " ); System.out.print( "Enter a number: " ); aNumber = keyboard.readDouble( ); aNumber = keyboard.readDouble( ); } }
9
2-9 Special Symbols a special symbol is one or two character sequences no spaces = ( ) { ; } ==. >= = ( ) { ; } ==. >= some special symbols mean different things in different contexts with two integers, + means addition 2 + 5 is the integer 7 with two strings, + mean concatenation "2" + "5" is the string "25"
10
2-10 Identifiers An identifier is a collection of certain characters that could mean a variety of things There are some identifiers that are part of Java: sqrt String Integer System in out sqrt String Integer System in out The programmer can make up new identifiers test1 x1 aNumber MAXIMUM A_1 test1 x1 aNumber MAXIMUM A_1
11
2-11 Identifiers Active Learning #1 answers at end Identifiers have from 1 to many characters: 'a'..'z', 'A'..'Z', '0'..'9', '_', $ identifiers start with letter a1 is legal, 1a is not can also start with underscore or dollar sign: _ $ Java is case sensitive. A and a are different. #1 Which of these are valid identifiers? a) abc e) $$$ i) a_1 a) abc e) $$$ i) a_1 b) m/h f) 25or6to4 j) student Number b) m/h f) 25or6to4 j) student Number c) main g) 1_time k) String c) main g) 1_time k) String d) double h) first-name l) ______ d) double h) first-name l) ______
12
2-12 Keywords A keyword is a word like token with a pre-defined meaning that can't be changed ( it is reserved) double int double int Other Java keywords not a complete list booleandefaultfor new booleandefaultfor new breakdoif private breakdoif private casedoubleimport public casedoubleimport public catchelseinstanceOf return catchelseinstanceOf return charextendsint void charextendsint void classfloatlong while classfloatlong while
13
2-13 Literals -- Java has 6 varieties Floating-point literals 1.234 -12.5 0.0 0..0 1e10 0.1e-5 String literals "character between double quotes" "another" "_" Integer literals -1 0 1 -2147483648 2147483647 -1 0 1 -2147483648 2147483647 Boolean literals (there are only two) true false true false Null (there is only one) null null Character literals 'A' 'b' '\n' '1' ' ' 'A' 'b' '\n' '1' ' '
14
2-14 Comments Example comments ( there are three kinds ) // on one line or // on one line or /* /* between slash star and star slash between slash star and star slash you can mash lines down real far you can mash lines down real far */ */ /** javadoc (or doc) comments for external documentation /** javadoc (or doc) comments for external documentation * @return The square root of x * @return The square root of x */ */ Provides internal documentation to explain program Provides external documentation via javadoc Helps programmers understand code--including their own
15
2-15 Primitive Numeric Types Java has several primitive types for storing numbers Stores integers in int variables Store floating-point numbers in double variables Operations with numeric variables: Declaration & Bring in a variable name and Initialization optionally give it value Assignment Modify the value of a variable Arithmetic+, -, * (multiplication), /
16
2-16 Declaration and Initializations Declare and give initial value: class-name identifier = initial-value ; class-name identifier = initial-value ; // For primitive types like int and double // For primitive types like int and double Example public class InitializeThreeVariables public class InitializeThreeVariables { public static void main( String[] args ) public static void main( String[] args ) { int credits = 0; int credits = 0; double points = 0.0; double points = 0.0; double GPA = 0.0; double GPA = 0.0; } }
17
2-17 Input / Output Programs must communicate with users This can be done with keyboard input messages screen output messages or mouse, or GUIs, or LUIs language user interface A Java message is composed of several components properly grouped together to perform some operation
18
2-18 Messages Some messages evaluate to some value that will be used by some other part of the program Other messages just go off and perform some activities Our first messages displays things to the computer screen, an object known as System.out next slide
19
2-19 Output messages General forms for doing output: System.out.print( exp-1 + exp-2,..., + exp-n ) ; System.out.print( exp-1 + exp-2,..., + exp-n ) ; System.out.println( exp-1 + exp-2,..., + exp-n ) ; System.out.println( exp-1 + exp-2,..., + exp-n ) ; Examples System.out.print( "Enter test 1: " ); System.out.print( "Enter test 1: " ); System.out.println( "Grade: " + courseGrade ); System.out.println( "Grade: " + courseGrade ); in a print statement, the expression is displayed + concatenates expressions into one string argument exp-1, exp-n may be any of the literals, a variable, an arithmetic expression such as (5*6-1), a message...
20
2-20 Active Learning #2 public class ShowMeTheOutput { public static void main( String[] args ) public static void main( String[] args ) { double aDouble = 0.0; double aDouble = 0.0; System.out.println( "1234" ); System.out.println( "1234" ); System.out.println( 1234 ); System.out.println( 1234 ); System.out.println( (2.5 * 3) + (2 * 3) ); System.out.println( (2.5 * 3) + (2 * 3) ); System.out.println( "aDouble: " + aDouble ); System.out.println( "aDouble: " + aDouble ); }} #2 Write the exact output that will be generated by this program when run
21
2-21 Assignment The programmer can set the values of variables with assignment operations of this form: variable-name = expression ; Examples: double x; // Undefined variables double x; // Undefined variables int j; // can not be evaluated int j; // can not be evaluated j = 1; j = 1; x = j + 0.23; x = j + 0.23;
22
2-22 Memory before and after The primitive variables x and j are undefined at first Variable Initial Assigned Variable Initial Assigned Name ValueValue j?1 x?1.23 The expression to the right of = must be a value that the variable can store (assignment compatible) x = "oooooh nooooo, you can't do that"; // <-Error x = "oooooh nooooo, you can't do that"; // <-Error j = x; // <-Error, can't assign a float to an int j = x; // <-Error, can't assign a float to an int ? ? means undefined
23
2-23 Assignment Active Learning #3, #4, #5 double bill; double bill; #3 What is value for bill now? bill = 10.00; bill = 10.00; bill = bill + ( 0.06 * bill ); bill = bill + ( 0.06 * bill ); #4 What is value for bill now? #4 What is value for bill now? #5 Which letters represent valid assignments? #5 Which letters represent valid assignments? String s = "abc"; String s = "abc"; int n = 0; int n = 0; double x = 0.0; double x = 0.0; a) s = n; e) n = 1.0; b) n = x; f) x = 999; c) x = n; g) s = "abc" + 1; d) s = 1; h) n = 1 + 1.5;
24
2-24 Input There are at least two options for reading numbers 1. use standard classes such as BufferedReader but this has complex code not robust: program terminates with bad numeric format 2. use the author-supplied TextReader class easy to use robust: asks users to try again on bad numeric format you write much less code hides a lot of complexity no need to explain exceptions, converting from String to int or double, Double and Integer classes, valueOf...
25
2-25 Author-supplied class TextReader At home, copy the file TextReader.java into your working folder. The file is: at this text book's Web site (linked from our home page) accessible from Harvill Lab -- no need to copy it there When you want input: Construct a TextReader object like this TextReader keyboard = new TextReader( ); TextReader keyboard = new TextReader( ); Then use the readInt and readDouble methods int anInt = keyboard.readInt(); int anInt = keyboard.readInt(); double aDouble = keyboard.readDouble(); double aDouble = keyboard.readDouble();
26
2-26 Input with TextReader When an input statement is encountered: the program pauses for user input the characters typed by the user are processed the message is replaced by the input number, which is then assigned to the variable to the left of = Example statements to get a number from the user TextReader keyboard = new TextReader( ); TextReader keyboard = new TextReader( ); System.out.print( "Enter credits: " ); System.out.print( "Enter credits: " ); int credits = keyboard.readInt( ); int credits = keyboard.readInt( ); Dialogue when the user enters 15 at the prompt Enter credits: 15 Enter credits: 15
27
2-27 Arithmetic Expressions Active Learning #6, #7 Arithmetic expressions consist of operators such as + - / * and operands such as 40, 1.5, payRate, and hoursWorked Example expression used in an assignment: grossPay = payRate * hoursWorked; grossPay = payRate * hoursWorked; Another example expression: (40 * payRate) + 1.5 * payRate * (hoursWorked - 40) (40 * payRate) + 1.5 * payRate * (hoursWorked - 40) For the previous expression #6 list all operators?___ #7 list all operands?___
28
2-28 Arithmetic Expressions a numeric variable double x = 1.2; a numeric variable double x = 1.2; or a numeric constant 100 or 99.5 or expression + expression1.0 + x or expression - expression 2.5 - x or expression * expression2 * x or expression / expression x / 2.0 or ( expression )(1 + 2.0) Arithmetic expression take many forms:
29
2-29 Boolean Expressions Boolean expressions evaluate to true or false Will often see relational operators Operator Meaning < < Less than > > Greater than <= <= Less than or equal to >= >= Greater than or equal to == == Equal to != != Not equal to
30
2-30 Boolean Expressions Active Learning #8, #9, #10 Some boolean expressions and their resulting values: double x = 4.0; double x = 4.0; Boolean Expression Value x < 5.0 true x < 5.0 true x > 5.0 false x > 5.0 false x <= 5.0 #8 What is the value? x <= 5.0 #8 What is the value? 5.0 == x #9 What is the value? 5.0 == x #9 What is the value? x != 5.0 #10 What is the value? x != 5.0 #10 What is the value?
31
2-31 Assign and Output Active Learning #11 Variables can be declared, initialized, and assigned a value. boolean ready = false; boolean able; double credits = 28.5; double hours = 9.5; // Assign true or false to all three boolean variables ready = hours >= 8.0; able = credits <= 32.0; System.out.println( "ready: " + ready ); System.out.println( "able: " + able ); #11 Write the output generated by the preceeding two printlns
32
2-32 Precedence of Arithmetic Operators Active Learning #12, #13 Expressions with more than one operator require some sort of precedence rules: * / evaluated in a left to right order * / evaluated in a left to right order - + evaluated in a left to right order in the absence of parentheses - + evaluated in a left to right order in the absence of parentheses #12 Evaluate 2.0 + 4.0 - 6.0 * 8.0 / 6.0 Use (parentheses) for readability or to intentionally alter an expression: double C, F; double C, F; F = 212.0; F = 212.0; C = 5.0 / 9.0 * (F - 32); C = 5.0 / 9.0 * (F - 32); #13 What is the current value of C ? #13 What is the current value of C ?
33
2-33 public class ThreeNumbers { public static void main( String[] args ) public static void main( String[] args ) { // 0. Initialize some variables, construct an object { // 0. Initialize some variables, construct an object double x = 0.0, y = 0.0, z = 0.0, average = 0.0; double x = 0.0, y = 0.0, z = 0.0, average = 0.0; TextReader keyboard = new TextReader( ); TextReader keyboard = new TextReader( ); // 1. Prompt for and get input from the user // 1. Prompt for and get input from the user System.out.print( "Enter 3 numbers: " ); System.out.print( "Enter 3 numbers: " ); x = keyboard.readDouble( ); x = keyboard.readDouble( ); y = keyboard.readDouble( ); y = keyboard.readDouble( ); z = keyboard.readDouble( ); z = keyboard.readDouble( ); // 2. Process: // 2. Process: average = ( x + y + z ) / 3.0; average = ( x + y + z ) / 3.0; // 3. Output: // 3. Output: System.out.println( "Average: " + average ); System.out.println( "Average: " + average ); }} Active Learning #14 Write the complete dialogue with input 2.3 5.0 2.0
34
2-34 2.4 Prompt and Input The Input/Process/Output algorithmic pattern can be used to help design many programs in the first several chapters. The Prompt and Input pattern also occurs frequently. The user is often asked to enter data The programmer must make sure the user is told what to enter
35
2-35 Prompt and Input Pattern
36
2-36 Examples Active Learning #15 Instances of the prompt and input pattern: System.out.println( "Enter x: " ); System.out.println( "Enter x: " ); double x = keyboard.readDouble( ); double x = keyboard.readDouble( ); System.out.println( "Enter y: " ); System.out.println( "Enter y: " ); double y = keyboard.readDouble( ); double y = keyboard.readDouble( ); System.out.println( "Enter z: " ); System.out.println( "Enter z: " ); double z = keyboard.readDouble( ); double z = keyboard.readDouble( ); #15 Write Java code that gets the current temperature from the user
37
2-37 Prompt and Input with a GUI import javax.swing.JOptionPane; // For showInputDialog public class PromptThenInput { public static void main( String[] args ) public static void main( String[] args ) { String numAsString = JOptionPane.showInputDialog( null, String numAsString = JOptionPane.showInputDialog( null, "Enter quality points: " ); "Enter quality points: " ); double qualityPoints = Double.parseDouble( numAsString ); double qualityPoints = Double.parseDouble( numAsString ); System.out.println( "You entered " + qualityPoints ); System.out.println( "You entered " + qualityPoints ); System.exit( 0 ); // needed with dialog box System.exit( 0 ); // needed with dialog box }}
38
2-38 Prompt and Input showInputDialog displays the String argument as the prompt in a modal dialog box: When the user presses enter, the message evaluates to the string in the input area.
39
2-39 int Arithmetic Active Learning #16, #17 int variables are similar to double, except they can only store whole numbers (integers) int anInt = 0; int anInt = 0; int another = 123; int another = 123; int NoCanDo = 1.99; // ERROR int NoCanDo = 1.99; // ERROR Division with integers is also different Perfoms quotient remainder whole numbers only anInt = 9 / 2; // anInt = 4, not 4.5 anInt = 9 / 2; // anInt = 4, not 4.5 anInt = anInt / 5; #16 What is anInt now? anInt = anInt / 5; #16 What is anInt now? anInt = 5 / 2; #17 What is anInt now? anInt = 5 / 2; #17 What is anInt now?
40
2-40 The integer % operation Active Learning #18, #19, #21, #22 The Java % operator returns the remainder. anInt = 9 % 2;// anInt ___ 1 ___ anInt = 9 % 2;// anInt ___ 1 ___ anInt = 101 % 2; #18 What is anInt now? anInt = 101 % 2; #18 What is anInt now? anInt = 5 % 11; #19 What is anInt now? anInt = 5 % 11; #19 What is anInt now? anInt = 361 % 60; #20 What is anInt now? anInt = 361 % 60; #20 What is anInt now? int quarter; int quarter; quarter = 79 % 50 / 25; #21 What is quarter? quarter = 79 % 50 / 25; #21 What is quarter? quarter = 57 % 50 / 25; #22 What is quarter now? quarter = 57 % 50 / 25; #22 What is quarter now?
41
2-41 2.5 The Math class Active Learning #23 Java defines a large collection of math functions. Math.sqrt( x ) // return the square root of x Math.sqrt( x ) // return the square root of x Math.abs( x ) // return absolute value of x Math.abs( x ) // return absolute value of x You call these methods by specifying the method name followed by argument(s) in parentheses: System.out.println( Math.sqrt( 4.0 ) ); System.out.println( Math.sqrt( 4.0 ) ); System.out.println( Math.abs( -2.34 ) ); System.out.println( Math.abs( -2.34 ) ); #23 What us the output from previous two lines? Method names must be preceded by an object name or a class name: Math is a class name.
42
2-42 Methods without objects Notice the previous calls precede the method name with the class (Math or JOptionPane) rather than an object: System.out.println( Math.abs( time1 ) ); System.out.println( Math.abs( time1 ) ); there is no object construction Math m = new Math( ); Math m = new Math( ); System.out.println( m.abs( time1 ) ); System.out.println( m.abs( time1 ) ); These are called static methods. not object-oriented However, Java does has a fair number of functionality implemented as static methods See Chapter 11 No constructors in Math (there is no state)
43
2-43 The pow method Active Learning #24 The pow method returns the first argument to the second argument's power. For example, Math.pow( 2.0, 3.0 ) returns 2 to the 3rd power (2 3 = 8.0). double base, power; double base, power; base = 2.0; base = 2.0; power = 4.0; power = 4.0; System.out.println( Math.pow( base, power) ); System.out.println( Math.pow( base, power) ); #18 What is output from the message above? #18 What is output from the message above? The following table shows some other Math methods. it is not a complete list
44
2-44 Some Math methods
45
2-45 Evaluate some method Calls Active Learning #25, #26, #27 Different arguments cause different return values: #25 Evaluate Math.sqrt( 16.0 ) #26 Evaluate Math.sqrt( Math.sqrt( 16 ) ) #27 Evaluate Math.round( 3.99 )
46
2-46 Errors Categories of errors and warnings are detected during implementation: 1. Compiletime errors 2. Exceptions 3. Intent errors You will experience many errors.
47
2-47 Compilation and Execution
48
2-48 Errors Detected at Compiletime Errors are detected an reported while the compiler is reading the source code. Compiler reports violations of syntax rules. Consider the general form for variable declarations: variable-declaration data type identifier-list ; identifier-list: identifier -or- -or- identifier-1, identifier-2, identifier-3,..., identifier-n
49
2-49 Pretend you are the compiler Active Learning #28 What should the compiler do when it is processing this source code? int student Number; int student Number; student = keyboard.readInt(); student = keyboard.readInt(); The variable declaration is incorrect. #28 Is there a missing comma or an extra space I don't know is a good answer I don't know is a good answer the compiler does not know what you want it thinks you meant to end the variable declaration C:\TokenizedProgram.java:9: ';' expected. C:\TokenizedProgram.java:9: ';' expected. int student Number; int student Number; ^
50
2-50 A few common compiletime errors Splitting an identifier: int my Weight = 0; int myWeight = 0; int my Weight = 0; int myWeight = 0; Misspelling a keyword: integer sum = 0; int sum = 0; integer sum = 0; int sum = 0; Leaving off a semicolon: double x = 0.0 double x = 0.0; double x = 0.0 double x = 0.0; Not closing a string constant: System.out.print( "Hi ); System.out.print( "Hi" ); System.out.print( "Hi ); System.out.print( "Hi" ); Forgetting parentheses: keyboard.readDouble; keyboard.readDouble( ); keyboard.readDouble; keyboard.readDouble( );
51
2-51 Exceptions Exceptions are errors that occur while the program is running. Exceptions are thrown when the program encounters something it could not handle well. For example: Invalid numeric input: if you use keyboard.readInt() you avoid the exception, so the next slide uses standard input to show what happens
52
2-52 The "standard" way to read ints Code we don't not need with TextReader import java.io.*; public class DemonstrateException { public static void main( String[] args ) public static void main( String[] args ) throws IOException throws IOException { int anInt; int anInt; BufferedReader input = new BufferedReader(new BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); InputStreamReader(System.in)); System.out.print( "Enter n: " ); System.out.print( "Enter n: " ); // Read an integer // Read an integer anInt = Integer.parseInt( input.readLine( ) ); anInt = Integer.parseInt( input.readLine( ) ); System.out.print( "You entered " + anInt ); System.out.print( "You entered " + anInt ); }}
53
2-53 NumberFormatException Here is the output (shortened) when Java throws an exception when parseInt attempts to convert BAD into an integer: Enter an integer: BAD Java.lang.NumberFormatException BAD java.lang.integer.parseInt(Integer.java:229) java.lang.integer.parseInt(Integer.java:229) java.lang.integer.parseInt(Integer.java:276) java.lang.integer.parseInt(Integer.java:276) at DemonsrateException.main at DemonsrateException.main (DemonsrateException.java:14) (DemonsrateException.java:14) The program terminates before it was supposed to. If you designed Java, how would you handle a BAD number the user may enter?
54
2-54 Intent Errors Active Learning #29 When the program does what you typed, not what you intended. Imagine this code: System.out.print( "Enter sum: " ); System.out.print( "Enter sum: " ); n = keyboard.readInt( ); n = keyboard.readInt( ); System.out.print( "Enter n: " ); System.out.print( "Enter n: " ); sum = keyboard.readDouble( ); sum = keyboard.readDouble( ); average = sum / n; average = sum / n; #29 Whose responsibility is it to catch this error?
55
2-55 When the software doesn't match the specification If none of the preceding errors occur, the program may still not be right. The working program may not match the specification because either: The programmers did not understand the problem statement the programmers failed to do what was asked The problem statement may have been incorrect Someone may have changed the problem statement Also, the specification could be wrong!
56
2-56 Answers to Active Learning Questions 1. (2-12) a, c, e, i, k, l 2. (2-20) 1234 1234 1234 13.5 13.5 aDouble: 0.0 aDouble: 0.0 3. (2-23) undefined 4. (2-23) 10.6 5. (2-23) c, f, g 6. (2-27) * + * * - 7. (2-27) 40 payrate 1.5 payrate hoursWorked payrate hoursWorked 8. (2-30) true 9. (2-30) false 10.(2-30) true 11.(2-31) ready: true able: true able: true 12.(2-32) -2 13.(2-32) 100 14.(2-33) Enter 3 numbers: 2.3 5.0 2.0 Average: 3.1 15. (2-36) System.out.print( "Enter current temperature: " ); "Enter current temperature: " ); double currentTemp = keyboard.readDouble( ); = keyboard.readDouble( ); 16. (2-39) 0 17. (2-39) 2 18. (2-40) 1 19. (2-40) 5 20. (2-40) 1 21. (2-40) 1 22. (2-40) 0 23. (2-41) 2.0 2.34 2.34 24. (2-43) 16.0 25. ( 2-45) 4.0 26. ( 2-45) 2.0 27. ( 2-45) 4 (an integer) 28 (2-49) I don't know, nor will the compiler nor will the compiler 29. (2-54) You, the programmer
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.