Вы находитесь на странице: 1из 48

Chapter 2: Elementary Programming

Introduction to Java Programming, Daniel Liang, 8th Edition

Spring 2012 2013

Writing Simple Programs

Writing programs to solve specific problem requires:


1. 2.

Developing an Algorithm: Write it using Pseudo code Translating the algorithm into Java code

Example: Write a program that computes the area of a circle:

Algorithm:

Read in radius (input) Compute area = radius * radius * Display the area (output)

Fatima Kanj, Spring 2012 - 2013

Writing Simple Programs: ComputeArea

Translate algorithm into java code:


class main method Variables:


Names: Descriptive (radius, area) Data types (Floating point numbers)

Compute the area = radius * radius * Print out the area using System.out.println

Introduce the concatenation operator

Fatima Kanj, Spring 2012 - 2013

Writing Simple Programs: ComputeArea

Translate algorithm into java code:

Fatima Kanj, Spring 2012 - 2013

Trace it:
radius no value area no value

radius 20.0

area 1256.636

Fatima Kanj, Spring 2012 - 2013

Reading Input from the Console

Input (Keyboard) Vs. Output (Monitor) To display output on the console:


System.out.print or println println method prints the parameter and advances the cursor to a new line.

To read input from via the keyboard:

Use the Scanner class


Scanner input = new Scanner(System.in);

Class
6

Variable of type Scanner

Creates an object of type Scanner

Fatima Kanj, Spring 2012 - 2013

Reading Input from the Console


Different methods can be used by the Scanner object to read data of different types:

Fatima Kanj, Spring 2012 - 2013

Reading Input from the Console: Compute Area

Fatima Kanj, Spring 2012 - 2013

Another Simple Program: ComputeAverage

Write a program that reads three numbers from the user and displays their average.

Fatima Kanj, Spring 2012 - 2013

Output of ComputeAverage

10

Fatima Kanj, Spring 2012 - 2013

Identifiers

These are used to name programming entities such as variables, constants, methods, classes, and packages.

Example: radius (variable), Welcome (class), println (method), etc.

The rules to choose an identifier:

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

1. Use descriptive names. 2. Java is case sensitive (area Area AREA)

11

Variables

Variables are used to store data and their values can change:

12

Fatima Kanj, Spring 2012 - 2013

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:

Assign initial values, example:


int x = 10; double radius = input.nextDouble(); //initial value is read from the console

13

Fatima Kanj, Spring 2012 - 2013

Assignment Statements and Expressions

Assignment Operator: Equal Sign ( = ) variable = expression


int x = 1; // Assign 1 to variable x; double radius = 1.0; // Assign 1.0 to variable radius; x = 5 * (3 / 2) + 3 * 2; //Assign the value of the expression to x; x = y + 1; // Assign the addition of y and 1 to x; area = radius * radius * 3.14159; // Compute area

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;

Remark: Constants are named in UPPERCASE: PI not Pi or pi

15

Fatima Kanj, Spring 2012 - 2013

Benefits of Constants

There are three benefits of using 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

Fatima Kanj, Spring 2012 - 2013

Primitive Data Types

Numeric Data Types:

byte, short, int, long, float, double

Character Data Type

Char

Boolean Data Type

boolean

17

Fatima Kanj, Spring 2012 - 2013

Primitive Data Types


Name Size (bits) Range -128 to 127 // -27 27- 1 -32768 to 32767 // -215 215- 1 -2147483648 to 2147483647 // -231 231- 1 -263 263- 1 +/- 1.4023x10-45 to 3.4028x10+38 Notes

byte short int long float double char boolean

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

+/- 4.9406x10-324 to 1.7977x10308 0 to 65535 (216 - 1) true or false

18

Fatima Kanj, Spring 2012 - 2013

Numeric Data Types and Operations


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

Fatima Kanj, Spring 2012 - 2013

Evaluating Arithmetic Expressions

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

Fatima Kanj, Spring 2012 - 2013

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

int i = 34; double d = 5.0;

Integer Literals: Default is to be considered of type (int) unless specified


System.out.println (2147483648) error System.out.println (2147483648L) correct, L denotes a long type

Floating-Point Literals: default is to be considered of type (double) unless specified

100.2f or 100.2F
Fatima Kanj, Spring 2012 - 2013

23

Problem: FahrenheitToCelsius

24

Fatima Kanj, Spring 2012 - 2013

Shorthand Operators

25

Fatima Kanj, Spring 2012 - 2013

Increment and Decrement Operators

double x = 1.0; double y = 5.0; double z = x + (++y); After all three lines are executed:

y = 6.0 z = 7.0 x = 0.0


26 Fatima Kanj, Spring 2012 - 2013

Numeric Type Conversions (Casting)

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

Fatima Kanj, Spring 2012 - 2013

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

Fatima Kanj, Spring 2012 - 2013

The char Type

Declaring and assigning values Special characters Conversion between char and numeric types

29

Fatima Kanj, Spring 2012 - 2013

Character Data Type char


char letter = 'A'; char numChar = '4';

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'.

char letter = 'A'; char letter = '\u0041';

30

Fatima Kanj, Spring 2012 - 2013

Reading a Character from the Console

There is no straightforward method to read single characters from the console (input is a Scanner object):

char letter = input.nextChar( ); //This is WRONG

char letter = input.next().charAt(0); //This is correct

Read a String

Get the first character in it

31

Fatima Kanj, Spring 2012 - 2013

Casting Between char and Numeric Types

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

char c = (char)65.25; // decimal 65 is assigned to t System.out.println(c); // Output: A

32

Fatima Kanj, Spring 2012 - 2013

Note

33

Fatima Kanj, Spring 2012 - 2013

Escape Sequences for Special Characters


Character Escape Sequence Name Unicode Code

\b \t \n \f \r \\ \' \"

Backspace Tab Linefeed Formfeed Carriage Return Backslash Single Quote Double Quote

\u0008 \u0009 \u000A \u000C \u000D \u005C \u0027 \u0022

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

The String Type

Declaring and assigning values Reading Strings


Using next() Using nextLine()

Converting strings to numbers

35

Fatima Kanj, Spring 2012 - 2013

The String Type


String message;
//Declare a string variable message

message = "Welcome to Java"; //assign a string to it


// Three strings are concatenated String message = "Welcome" + "to" + "Java"; // String Chapter is concatenated with number 2 String s = "Chapter" + 2; // Output: Chapter2 // String Supplement is concatenated with character B String s1 = "Supplement" + 'B'; // Output: SupplementB int i = 1; int j = 2; System.out.println("i + j is " + i + j); //Output: i + j is 12 System.out.println("i + j is " + (i + j));//Output: i + j is 3
36 Fatima Kanj, Spring 2012 - 2013

Reading Strings (Using next())

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

Reading Strings (Using nextLine())

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

Converting Strings to Numbers

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:

Use the parseInt method in the Integer class, as follows:


String strNum = scan.next(); int intValue = Integer.parseInt(strNum );

Use the parseDouble method in the Double class, as follows:


String strNum = scan.next(); double doubleValue = Double.parseDouble(strNum);

39

Fatima Kanj, Spring 2012 - 2013

Programming Style and Documentation

Appropriate Comments and Comments Styles Naming Conventions Proper Indentation and Spacing Lines Block Styles

40

Fatima Kanj, Spring 2012 - 2013

Comments

javadoc: /** ................ . */


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.

line comments: //.

Use them for commenting on steps inside a 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

Variables and method names:


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.

Class: Capitalize the first letter of each word in a class name:

ComputeArea, Math, JOptionPane.

Capitalize every letter in a constant, and use underscores between words: PI and MAX_VALUE.
42 Fatima Kanj, Spring 2012 - 2013

Proper Indentation and Spacing

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

Fatima Kanj, Spring 2012 - 2013

Programming Errors

Syntax Errors

Detected by the compiler

Runtime Errors

Causes the program to abort

Logic Errors

Produces incorrect result

45

Fatima Kanj, Spring 2012 - 2013

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

Fatima Kanj, Spring 2012 - 2013

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

Fatima Kanj, Spring 2012 - 2013

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

Fatima Kanj, Spring 2012 - 2013

Вам также может понравиться