Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Lambert / Osborne Objectives Construct and use numeric and string literals. Name and use variables and constants. Create arithmetic expressions. Understand the precedence of different arithmetic operators. Concatenate two strings or a number and a string. Know how and when to use comments in a program. Chapter 3
2 Lambert / Osborne Fundamentals of Java 4E Objectives (continued) Tell Chapter 3 3 the difference between syntax errors, run-time errors, and logic errors. Insert output statements to debug a program. Understand the difference between Cartesian coordinates and screen coordinates. Work with color and text properties. Lambert / Osborne Fundamentals of Java 4E
logic error method signature origin package Fundamentals of Java 4E Vocabulary (continued) Chapter 3 5 pseudocode syntax reserved syntax words
run-time error screen coordinate system semantics Lambert / Osborne errors variable declaration statement virus Fundamentals of Java 4E Language Elements Programming and natural languages share three elements. Chapter 3
Vocabulary: Words and symbols Syntax: Rules for combining statements. Use 6 of operators, parentheses, etc. Semantics: Rules for interpreting statements. Order of precedence Lambert / Osborne Fundamentals of Java 4E Language Elements (continued) Programming Chapter 3
Vs. Natural Languages: Programming and natural languages have three differences. Size: small vocabulary, simple syntax. Rigidity: Syntax must be absolutely correct. Literalness: Computers follow exact instructions. It is difficult to express complex ideas using limited syntax and semantics of programming languages. 7 Lambert / Osborne Fundamentals of Java 4E
Basic Java Syntax and Semantics Data Chapter 3 Types: Primitive: numbers, characters, Booleans Objects: scanners, strings, and more Syntax: Syntax differs for objects and primitive data. 8 Primitive: data types are combined in expressions with operators (addition, multiplication) Objects: sent messages, must be instantiated before use Lambert / Osborne Fundamentals of Java 4E Basic Java Syntax and Semantics
(continued) Numbers: Chapter 3 9 Numeric data types: Most programs input numeric data, perform calculations, output numeric results. Java includes six numeric data types but we use two: Lambert / Osborne Fundamentals of Java 4E Basic Java Syntax and Semantics (continued) Literals:
Chapter 3 Literals are items in a program whose values do not change. Restricted to primitive data types and strings. Examples of numeric literals 10 Lambert / Osborne Fundamentals of Java 4E Basic Java Syntax and Semantics (continued) Variables Chapter 3 11
and Their Declarations: Variables are items whose values can change during execution. Changing the value of a variable Lambert / Osborne Fundamentals of Java 4E Basic Java Syntax and Semantics (continued) Chapter 3 12 Variables and Their Declarations (cont): Before using a variable, the program must declare its type.
Variable declaration statement Type on left; variable name on right Several variables and values can be in the same statement. Lambert / Osborne Fundamentals of Java 4E Basic Java Syntax and Semantics (continued) Variables Chapter 3 13 and Their Declarations (cont): Instantiation creates objects.
Constants are variables that, once initialized, cannot change. Lambert / Osborne Fundamentals of Java 4E Basic Java Syntax and Semantics (continued) Assignment Chapter 3 statements have variables on the left and values on the right. Arithmetic expressions are operands and operators. 14
Multiplication/division before addition/subtraction. Equal operators calculated from left to right. Use parentheses to change the order. Lambert / Osborne Fundamentals of Java 4E Basic Java Syntax and Semantics (continued) Explanation Chapter 3 15 about points concerning operators:
Division has different semantics for integer and floatingpoint operands. % yields the remainder of one number divided by another. Java applies operators of higher precedence over lower precedence. Parentheses must occur in pairs, but can be nested. Lambert / Osborne Fundamentals of Java 4E Basic Java Syntax and Semantics (continued) Chapter 3 16 Maximum, Minimum, and Arithmetic Overflow: Numeric data types support a finite range of values. Programmers use constants to represent value range.
Arithmetic overflow: when values are outside of range. JVM inverts the sign of the number and allows the number to continue. Lambert / Osborne Fundamentals of Java 4E Basic Java Syntax and Semantics (continued) Mixed-Mode Chapter 3 17 Arithmetic: In Java, integers are converted to doubles (floating-point) when mixed. Casting to int and double: Casting allows data types to be converted. The cast operator has higher precedence.
Cast operators are useful for rounding floatingpoint numbers to integers. Lambert / Osborne Fundamentals of Java 4E Basic Java Syntax and Semantics (continued) String Chapter 3 Expressions and Methods: Strings can be literals or assigned to variables. Strings can also be combined using concatenation operator and be sent messages. 18 Combine field names first name and last name to produce Bill Smith. Strings can be concatenated to numbers.
Lambert / Osborne Fundamentals of Java 4E Basic Java Syntax and Semantics (continued) Chapter 3 String Expressions and Methods (cont): Escape character (\) is used to indicate that a quotation mark is to be taken literally, not as a delimiter. 19 Used to have commas and quotations in output.
Escape also used to indicate tabs (\t) and more. If \ is needed in a string, use two (\\). A string returns its length in response to a length message. Lambert / Osborne Fundamentals of Java 4E Basic Java Syntax and Semantics (continued) Methods, Chapter 3 Messages, and Signatures: An object can respond to a message only if its class implements a corresponding message (same name). What type of value it returns
Its name The number and type of parameters it expects 20 To use a method, you must know: A methods name and the types and numbers of its parameters are called the methods signature. Lambert / Osborne Fundamentals of Java 4E Basic Java Syntax and Semantics (continued) Chapter 3
User-Defined Symbols: Variable and program names are examples of userdefined symbols. User-defined symbols consist of a letter (A Z), (a z), (_ and $), followed by a sequence of letters and/or digits (0 9). Names are case-sensitive. Keywords and reserved words cannot be used as they have special meaning. 21 Else, byte, char, do, return, and more Lambert / Osborne Fundamentals of Java 4E Basic Java Syntax and Semantics (continued) Packages
Chapter 3 and the import Statement: Packages allow programmers to share code. Packages are collections of classes that can be imported into a program. An import statement form is: 22 x is the package name y is the subsection in the package z is the class in the package Lambert / Osborne Fundamentals of Java 4E Terminal I/O for Different Data Types Objects Chapter 3
support terminal I/O. An instance of the Scanner class supports input and the object System.out supports output. System.out is an instance of the class PrintStream. 23 This class and others are available to Java programmers without using import statements. Lambert / Osborne Fundamentals of Java 4E Terminal I/O for Different Data Types (continued) When Chapter 3 24
a program encounters an input statement, it pauses and waits for the user to press Enter, then processes the users input. Interaction with user (bold) looks like this: Lambert / Osborne Fundamentals of Java 4E Comments Comments Chapter 3 25 are explanatory sentences inserted in a program used to clarify code and are ignored by the compiler. End of line comments (followed by //)
Multi-line comments (opened by /* and closed by */) Lambert / Osborne Fundamentals of Java 4E Comments (continued) To Chapter 3 26 make a program readable: Begin with a statement of purpose. Use comments to explain variables purposes. Precede major segments of code with brief
comments. Include comments to explain complex or tricky code sections. Lambert / Osborne Fundamentals of Java 4E Programming Errors The Three Types of Errors: Syntax errors are detected at compile time. Chapter 3 Run-time errors are when a computer is asked to do something illegal.
27 Missing semi-colon or misspelling. Divide by 0. Null pointer: sending a message to uninstantiated object. Java is case-sensitive, so Main and main are different. Lambert / Osborne Fundamentals of Java 4E Programming Errors (continued) The Chapter 3 Three Types of Errors (cont): Logic errors occur when we fail to express ourselves accurately.
28 Tell someone to turn left, but we mean to say right. Detected by incorrect output. Use test data to compare output with expected results. Desk checking: rereading code carefully. Lambert / Osborne Fundamentals of Java 4E Debugging After Chapter 3 29
a bug is detected, you must find it. Could reread the code, but the logic error is hard to find and detect. Debug: Add lines of code to print values of variables in the terminal window, then run the program again. Lambert / Osborne Incorrect output from the temperature conversion program Fundamentals of Java 4E Graphics and GUIs: Drawing Shapes and Text Defining Chapter 3 a Specialized Panel Class: An application window in a GUI program has a
defined set of responsibilities. Before we create and display other objects, ask which object will be responsible for them. The application window or the panel in which they appear Divide 30 the labor and delegate responsibility. Define a new panel by creating a new class Lambert / Osborne Fundamentals of Java 4E Graphics and GUIs: Drawing Shapes and Text (continued) Coordinate
Chapter 3 31 Systems: Positions in this system are specified in terms of points with x and y coordinates relative to the origin (0,0). Java uses a screen coordinate system. Lambert / Osborne Fundamentals of Java 4E Graphics and GUIs: Drawing Shapes and Text (continued) The Chapter 3 Graphics Class: The package java.awt provides a Graphics class for drawing in a panel. A panel maintains an instance of this class, called a graphics context.
Allows program to access and modify a panels bitmap Each shape is drawn in a graphics context with a foreground color (black default). 32 Lambert / Osborne Fundamentals of Java 4E Graphics and GUIs: Drawing Shapes and Text (continued) Sample method in the Graphics class: Chapter 3
33 Lambert / Osborne Fundamentals of Java 4E Graphics and GUIs: Drawing Shapes and Text (continued) Drawing Shapes with the Method paintComponent: The responsibilities of a panel class: Chapter 3 When a window opens, the JVM sends the message paintComponent to each object.
34 Draw images in response to messages from the application Redraw images when window is refreshed Objects with images to draw do so The application does not call paintComponent; it is triggered by the JVM in response to events. Lambert / Osborne Fundamentals of Java 4E Graphics and GUIs: Drawing Shapes and Text (continued) Chapter 3
35 Finding the Width and Height of a Panel: Find the width and height to center an image on a panel and keep it centered when window resizes. Use getWidth() and getHeight(). Text Properties and the Font Class: In a bitmapped display, text is drawn like an image. Lambert / Osborne Fundamentals of Java 4E Summary Chapter 3 In this chapter, you learned: Java programs use the int data type for whole numbers (integers) and double for floatingpoint numbers (numbers with decimals). Java variable and method names consist of a letter followed by additional letters or digits.
Java keywords cannot be used as names. 36 Lambert / Osborne Fundamentals of Java 4E Summary (continued) Final Chapter 3 37 variables behave as constants; their values cannot change after they are declared. Arithmetic expressions are evaluated according to precedence. Some expressions yield different results for integer and floatingpoint operands. Strings may be concatenated to form a new string. Lambert / Osborne Fundamentals of Java 4E
Summary (continued) Chapter 3 The compiler catches syntax errors. The JVM catches run-time errors. Logic errors, if they are caught, are detected by the programmer or user of the program at run time. A useful way to find and remove logic errors is to insert debugging output statements to view the values of variables. 38 Lambert / Osborne Fundamentals of Java 4E Summary (continued) Java Chapter 3
39 uses a screen coordinate system to locate the positions of pixels in a window or panel. The origin of this system is in the upper-left corner or the drawing area, and the x and y axes increase to the right and downward, respectively. The programmer can modify the color with which images are drawn and the properties of text fonts for a given graphics object. Lambert / Osborne Fundamentals of Java 4E
APORTES DE SHIGEO SHINGO NIVELES DE PREVENCIÓN POKA-YOKE. NIVELES DE PREVENCIÓN DE POKA- YOKE: Nivel 6 (A prueba de errores): El uso de una variedad de dispositivos para verificar el cien por ciento de los productos, de manera que estén...
Demand Management Dr. Ron Lembke SCM 461 Role of Demand Management Collect information from all demand sources Customers Spare parts Negotiate and Confirm shipping dates, quantities Confirm order status, communicate changes Different Environments Factory to customers - plant very aware...
Supplier Relationships. Can diversity be a competitive advantage?. Whether buying goods and services in China, South America, India, etc. the ability to deal with suppliers in their own language, in appropriate behavioral manners, and to conduct successful negotiations may be...
Facts linked to child neglectChildren from low-income families are 4 times more likely to experience mental health problems than children from higher-income families.(Morrison Gutman et al., 2015) 75% of adults with a diagnosable mental health problem experience the first symptoms...
Dialectical Materialism. Marxism. Marx's theories about society, economics and politics—collectively known as Marxism—hold that all societies progress through the dialectic of class struggle: a conflict between an ownership class which controls production and a lower class which produces the ...
Lead Facilitator Training. ... completion of team's workshop report and sending it to the regional coordinator and the Operations Committee, ensuring appropriate steps are taken regarding participants who show an interest in becoming facilitators. ... MANSELL, PAUL ...
Brazil What I would like to explore the most is the Africa Diaspora and why there is such a huge difference within both countries. In one place the culture has nearly died out whereas the other flourishes with African culture...
Ready to download the document? Go ahead and hit continue!