Docsity

Elementary Programming in Java: Lecture Notes and Exercises, Exercises of Programming Paradigms

Partial preview of the text

Download Elementary Programming in Java: Lecture Notes and Exercises and more Exercises Programming Paradigms in PDF only on Docsity!

١١

Chapter 2 ELEMENTARYPROGRAMMING

Lecture notes for computer programming 1 Lecture notes for computer programming 1 Faculty of Engineering and Information TechnologyFaculty of Engineering and Information Technology

Prepared by: Prepared by:

Iyad^ AlbayoukIyadAlbayouk

٢٢

Objectives ■ To write Java programs to perform simple computations (§2.2). ■ To obtain input from the console using the Scanner class (§2.3). ■ To use identifiers to name variables, constants, methods, and classes (§2.4). ■ To use variables to store data (§§2.5–2.6). ■ To program with assignment statements and assignment expressions (§2.6). ■ To use constants to store permanent data (§2.7). ■ To name classes, methods, variables, and constants by following their naming conventions(§2.8). ■ To explore Java numeric primitive data types: byte, short, int, long, float, and double (§2.9.1). ■ To perform operations using operators +, -, *, /, and % (§2.9.2). ■ To perform exponent operations using Math.pow(a, b) (§2.9.3). ■ To write integer literals, floating-point literals, and literals in scientific notation (§2.10). ■ To write and evaluate numeric expressions (§2.11). ■ To obtain the current system time using System.currentTimeMillis() (§2.12). ■ To use augmented assignment operators (§2.13). ■ To distinguish between postincrement and preincrement and between postdecrement andpredecrement (§2.14). ■ To cast the value of one type to another type (§2.15). ■ To describe the software development process and apply it to develop the loan paymentprogram (§2.16). ■ To represent characters using the char type (§2.17). ■ To represent a string using the String type (§2.18). ■ To obtain input using the JOptionPane input dialog boxes (§2.19).

٤٤

Writing a Simple Program ^ Writing a program involves designing a strategy forsolving the problem and then using a programminglanguage to implement that strategy. ^ Let’s first consider the simple problem of computing thearea of a circle. How do we write a program for solvingthis problem? ^ Writing a program involves designing algorithms andtranslating algorithms into programming instructions, orcode.

٥٥

Writing a Simple Program, cont. ^ The algorithm for calculating the area of a circle can bedescribed as follows:1. Read in the circle’s radius.2. Compute the area using the following formula:

area = radius * radius *

3. Display the result.

٧٧

Reading Input from the Console 1. Create a Scanner object^ Scanner scanner = new Scanner(System.in); 2. Use the methods next()

, nextLine(), nextByte()

nextShort()

, nextInt()

, nextLong()

, nextFloat()

nextDouble()

, or nextBoolean()

to obtain to a string that

ends before a whitespace character, string ending with the Enter key pressed, byte, short, int, long, float, double, or boolean value. For example,^ System.out.print("Enter a double value: ");Scanner scanner = new Scanner(System.in);double d = scanner.nextDouble();

٨٨

Reading Input from the Console, CONT. importimport^ java.util.Scannerjava.util.Scanner

; // Scanner is in the; // Scanner is in the

java.utiljava.util^

packagepackage

public classpublic class

ComputeAreaComputeArea

{{

public static void public static void

main(Stringmain(String

[]^ args) {[]args) {

// Create a Scanner object// Create a Scanner object^ Scanner input = newScanner input = new

Scanner(System.inScanner(System.in

););

// Prompt the user to enter a radius// Prompt the user to enter a radius^ System.out.print("EnterSystem.out.print("Enter

a number for radius: ");a number for radius: ");

double radius =double radius =

input.nextDoubleinput.nextDouble

();();

// Compute area // Compute areadouble area = radius * double area = radius *

radius^ * 3.14159;radius* 3.14159; // Display results // Display resultsSystem.out.println("The^ System.out.println("The

area for the circle of radius " +area for the circle of radius " + ^ This program computes the area of the circle with console input^ radius + " is " + area);radius + " is " + area); }} } }

١٠١٠

Identifiers • An identifier is a sequence of characters that consist ofletters, digits, underscores (), and dollar signs ($). • An identifier must start with a letter, an underscore (), ora dollar sign ($). It cannot start with a digit. • An identifier cannot be a reserved word. (See Appendix A,“Java Keywords,” for a list of reserved words). • An identifier cannot be

true

,^ false

, or^ null

Identifiers are the names that identify the elements suchas classes, methods, and variables in a program. All identifiers must obey the following rules:^ •^ An identifier can be of any length.

١١١١

Variables // Compute the

first

area

// Compute the

first

area

radius

radius

area =

radius

area =

radius

*^ radiusradius

System.out.println("The^ System.out.println("The

area

is

area

is^

“^ +“+

area +

" for radius "+radius);

area +

" for radius "+radius);

// Compute the

second

area

// Compute the

second

area

radius

radius

area =

radius

area =

radius

*^ radiusradius

System.out.println("The^ System.out.println("The

area

is

area

is^

“^ +“+

area +

" for radius "+radius);

area +

" for radius "+radius);

Variables are used to represent values that may be changed in the program.

١٣١٣

Assignment Statements x = 1;

// Assign 1 to x;

x = 1;

// Assign 1 to x;

double radius = 1.0;

// Assign 1.0 to radius;

double radius = 1.0;

// Assign 1.0 to radius;

a = 'A';

// Assign 'A' to a;

a = 'A';

// Assign 'A' to a;

int^ Y = 5 * (3 / 2); // Assign the value of the intY = 5 * (3 / 2); // Assign the value of the

expression to Y expression to Y

An assignment statement designates a value for a variable. Anassignment statement can be used as an expression in Java.^ The syntax for assignment statements is as follows:^ variable = expression;variable = expression;^ Here are some examples of

assignment statements

:

١٤١٤

Named Constants AND NamingConventions^ final

double

PI

=^

3.14159;

final

double

PI

=^

3.14159;

final^ final

intint

SIZE

=^

3; SIZE

=^

3;

A named constant is an identifier that represents a permanent value. Here is the syntax for declaring a constant: final^ final

datatypedatatype

CONSTANTNAME = value;CONSTANTNAME = value; Here are some examples of

a named constants

:

Naming conventions are a sticking with the Java namingconventions makes your programs easy to read and avoids errors.

١٦١٦

Numeric Operators Name^

Meaning

Example

Result

+^

Addition

34 + 1

35

-^

Subtraction

34.0 – 0.

*^

Multiplication

300 * 30

9000

/^

Division

1.0 / 2.

%^

Remainder

20 % 3

2

١٧١٧

Integer Division +, -, *, /, and %5 / 2 yields an integer 2.5.0 / 2 yields a double value 2.55 % 2 yields 1 (the remainder of the division)-7 % 3 yields -1, -12 % 4 yields 0, -26 % -8 yields -2,and 20 % -13 yields 7.

١٩١٩

Example: Displaying Time This program obtains minutes and remaining seconds froman amount of time in seconds. For example, 500 secondscontains 8 minutes and 20 seconds. import

java.util.Scanner; public class

DisplayTime { public static void

main(String[] args) { // Prompt the user for inputScanner input =

new^ Scanner(System.in); System.out.print("Enter an integer for seconds: "); int^ seconds = input.nextInt(); int^ minutes = seconds / 60; int^ remainingSeconds

= seconds % 60;

System.out.println(seconds + " seconds is " + minutes +" minutes and " + remainingSeconds + " seconds");} }

٢٠٢٠

NOTE Calculations involving floating-point numbers areapproximated because these numbers are notstored with complete accuracy. For example,System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 -

displays 0.5000000000000001, not 0.5, andSystem.out.println(1.0 -

displays 0.09999999999999998, not 0.1. Integersare stored precisely. Therefore, calculations withintegers yield a precise integer result.