Академический Документы
Профессиональный Документы
Культура Документы
Developing an Algorithm: Write it using Pseudo code Translating the algorithm into Java code
Algorithm:
Read in radius (input) Compute area = radius * radius * Display the area (output)
Compute the area = radius * radius * Print out the area using System.out.println
Trace it:
radius no value area no value
radius 20.0
area 1256.636
System.out.print or println println method prints the parameter and advances the cursor to a new line.
Class
6
Write a program that reads three numbers from the user and displays their average.
Output of ComputeAverage
10
Identifiers
These are used to name programming entities such as variables, constants, methods, classes, and packages.
A sequence of characters that consists of letters, digits, underscores (_), and dollar signs ($) BUT it CANNOT start with a digit. An identifier cannot be a reserved word. An identifier cannot have spaces. An identifier cannot be true, false, or null. Example: Legal Identifiers: $2, area, radius, showMessageDialog
Illegal identifiers:
2A and d+4.
Fatima Kanj, Spring 2012 - 2013
11
Variables
Variables are used to store data and their values can change:
12
Declaration of Variables
datatype variableName;
int x; // Declare x to be an integer variable; double radius; // Declare radius to be a double variable; char a; // Declare a to be a character variable;
If variables are of the same type, they can be declared together, as follows:
datatype variable1, variable2, ..., variablen; int i, j, k; // Declare i, j, and k as integer variables
Initialize variables:
int x = 10; double radius = input.nextDouble(); //initial value is read from the console
13
To assign a value to a variable, the variable name must be on the left of the assignment operator. 1 = x; Wrong
System.out.println(x = 1); Correct i = j = k = 1; Correct x = x + 1; Correct
The data type of the variable must be compatible with the data type of the value on the right: int x = 0.1; Wrong
14 Fatima Kanj, Spring 2012 - 2013
Named Constants
The value of a variable may change during the execution of a program, but a named constant or simply constant represents permanent data that never changes. If it is attempted to change in the program, an error occurs. final datatype CONSTANTNAME = VALUE;
15
Benefits of Constants
You dont have to repeatedly type the same value If you have to change the constant value (e.g., from 3.14 to 3.14159 for PI), you need to change it only in a single location in the source code. A descriptive name for a constant makes the program easy to read.
16
Char
boolean
17
8 16 32 64 32 64 16 1
Signed / whole-number Signed / whole-number Signed / whole-number Signed / whole-number Signed / Single-precision real-number Signed / Double-precision real- number Unsigned
18
Numeric Operators Evaluating Arithmetic Expressions Numeric Literals Shorthand Operators Increment & Decrement Operators Numeric Type Conversion
19 Fatima Kanj, Spring 2012 - 2013
Numeric Operators
Remarks:
The result of integer (int) division is an (int): 5/2 = 2 The sign of the modulus operators result follows the dividend: -7 % 2 = -1 and 7 % (-2) = 1 Unary Operator (1 operand -5) , Binary Operator (2 Operands 5-2) Floating-point numbers are not stored with complete accuracy (Special representation when converted to binary):
System.out.println(1.0-0.9); displays 0.09999999999999998, not 0.1.
20 Fatima Kanj, Spring 2012 - 2013
Arithmetic Expressions
A numeric expression in Java involves a straightforward translation of an arithmetic expression using Java operators. Example:
3+4 10 5 ( + 5 (3 + 4 ) / 5 10 5
+ )
21
Order of evaluation:
Parenthesis, then, *, /, % , If more than one operator then evaluation from left to right +, -, If more than one operator then evaluation from left to right
22
Numeric Literals
A literal is a constant value that appears directly in a program. The literal must be within the range of the datatype of the variable
100.2f or 100.2F
Fatima Kanj, Spring 2012 - 2013
23
Problem: FahrenheitToCelsius
24
Shorthand Operators
25
double x = 1.0; double y = 5.0; double z = x + (++y); After all three lines are executed:
Casting is an operation that converts a value of one data type into a value of another data type.
Widening: Casting small range variable larger range variable Narrowing: Casting large range variable smaller range variable
float f = (float)10.1; // double into float int i = (int)f; //float into int, i = 10
27
Casting Example
1 public class SalesTax { 2 3 4 5 6 7 } purchaseAmount = 197.55 tax = purchaseAmount * 0.06 = 197.55 * 0.06 = 11.853 OUTPUT: 11.85 } public static void main(String[] args) { double purchaseAmount = 197.55; double tax = purchaseAmount * 0.06; System.out.println((int)(tax * 100) / 100.0);
28
Declaring and assigning values Special characters Conversion between char and numeric types
29
Encoding Scheme: Defines how data is encoded in the computer (Unicode, ASCII). Java supports Unicode 2 bytes, preceded by \u, expressed in four hexadecimal digits that run from '\u0000' to '\uFFFF'.
30
There is no straightforward method to read single characters from the console (input is a Scanner object):
Read a String
31
A char can be cast into any numeric type, and vice versa.
int i = (int)'A'; // the Unicode of character A is //assigned to i System.out.println(i); // Output: 65
32
Note
33
\b \t \n \f \r \\ \' \"
Backspace Tab Linefeed Formfeed Carriage Return Backslash Single Quote Double Quote
System.out.println("He said Java is fun"); Output: He said Java is fun System.out.println("He said Java is fun"); Error!!! System.out.println("He said \"Java is fun\""); Output: He said Java is fun
34 Fatima Kanj, Spring 2012 - 2013
35
Remark: The next() method reads a string that ends with a whitespace character
(i.e., ' ', '\t', '\f', '\r', or '\n').
37 Fatima Kanj, Spring 2012 - 2013
Remarks:
1. The nextLine() method reads a string that ends with the Enter key pressed. 2. To avoid input errors, do not use nextLine() after nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble(), and next().
38 Fatima Kanj, Spring 2012 - 2013
If a number is read from the keyboard as a string, then this number can be converted into an integer or a double as follows:
39
Appropriate Comments and Comments Styles Naming Conventions Proper Indentation and Spacing Lines Block Styles
40
Comments
Use them at the beginning of your program to include a summary of the program, your name, instructor, date, etc. Use them for commenting an entire class or an entire method.
paragraph comment: /* */
41 Fatima Kanj, Spring 2012 - 2013
Naming Conventions
Your program will be better understood and youll be able to understand programs of other people. Choose meaningful and descriptive names.
numOfStudents
Use lowercase: radius, scanner. If the name consists of several words, concatenate all in one, use lowercase for the first, and capitalize the first letter of each subsequent word: computeArea, showInputDialog.
Capitalize every letter in a constant, and use underscores between words: PI and MAX_VALUE.
42 Fatima Kanj, Spring 2012 - 2013
A consistent indentation style makes programs clear and easy to read, debug, and maintain. Indentation is used to illustrate the structural relationships between a programs components or statements. Indent each subcomponent or statement at least two spaces more than the construct within which it is nested. Spacing Use blank line to separate segments of the code. Leave single spaces between operator:
43 Fatima Kanj, Spring 2012 - 2013
Block Styles
44
Programming Errors
Syntax Errors
Runtime Errors
Logic Errors
45
Syntax Errors
Here you might have two errors detected for one mistake commited; not declaring i.
public class ShowSyntaxErrors { public static void main(String[] args) { i = 30; System.out.println(i + 4); } }
46
Runtime Errors
Cause a program to terminate abnormally. Runtime errors occur while an application is running if the environment detects an operation that is impossible to carry out.
Input Errors: the user enters input which the program cannot handle. Division by zero: int i = 1/0;
47
Logic Errors
// ShowLogicErrors.java: The program contains a logic error public class ShowLogicErrors { public static void main(String[] args) { // Add number1 to number2 int number1 = 3; int number2 = 3; number2 += number1 + number2; System.out.println("number2 is " + number2); } }
48