Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.

Similar presentations


Presentation on theme: "1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from."— Presentation transcript:

1 1 1 Chapter 2 Elementary Programming

2 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from this chapter, you will learn how to solve practical problems programmatically. Through these problems, you will learn Java primitive data types and related subjects, such as variables, constants, data types, operators, expressions, and input and output.

3 3 3 Objectives To write Java programs to perform simple calculations (§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 declare Java primitive data types: byte, short, int, long, float, double, and char (§§2.8.1). To use Java operators to write numeric expressions (§§2.8.2–2.8.3). To display current time (§2.9). To use short hand operators (§2.10). To cast value of one type to another type (§2.11). To compute loan payment (§2.12). To represent characters using the char type (§2.13). To compute monetary changes (§2.14). To represent a string using the String type (§2.15). To become familiar with Java documentation, programming style, and naming conventions (§2.16). To distinguish syntax errors, runtime errors, and logic errors and debug errors (§2.17). (GUI) To obtain input using the JOptionPane input dialog boxes (§2.18).

4 4 4 Introducing Programming with an Example Listing 2.1 Computing the Area of a Circle The algorithm for calculating the area of a circle can be described as follows: 1. Read in the circle’s radius. 2. Compute the area using the following formula: area = radius * radius * p 3. Display the result.

5 5 5 Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } no value radius memory no value area allocate memory for radius and area animation declaring variables Java provides simple (primitive) data types for representing integers, real numbers, characters, and Boolean types.

6 6 6 Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } 20 radius no value area assign 20 to radius animation

7 7 7 Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } 20 radius memory 1256.636 area compute area and assign it to variable area animation

8 8 8 Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } 20 radius memory 1256.636 area print a message to the console animation

9 9 9 Reading Input from the Console 1. Create a Scanner object Scanner input = new Scanner(System.in); 2. Use the methods next(), nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble(), or nextBoolean() to obtain to a string, byte, short, int, long, float, double, or boolean value. For example, System.out.print("Enter a double value: "); Scanner input = new Scanner(System.in); double d = input.nextDouble(); ComputeAreaWithConsoleInput Run ComputeAverage Run

10 10

11 11 Prompt Line 9 displays a string "Enter a number for radius: " to the console. This is known as a prompt, because it directs the user to enter an input. Your program should always tell the user what to enter when expecting input from the keyboard. Note: print vs. println 11

12 12

13 13

14 14 Identifiers An identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($). An identifier must start with a letter, an underscore (_), or a 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). For example An identifier cannot be true, false, or null. (they are reserved words) An identifier can be of any length. Use descriptive names

15 15 Example Which of the following identifiers are valid? Which are Java keywords? miles, Test, a++, ––a, 4#R, $4, #44, apps class, public, int, x, y, radius

16 16 Variables Variables are used to store values to be used later in a program. They are called variables because their values can be changed. // Compute the first area radius = 1.0; area = radius * radius * 3.14159; System.out.println("The area is “ + area + " for radius "+radius); // Compute the first area radius = 1.0; area = radius * radius * 3.14159; System.out.println("The area is “ + area + " for radius "+radius);

17 17 Declaring Variables int x; // Declare x to be an integer variable; double area; // Declare area to be a double variable; char a; // Declare a to be a character variable; To use a variable, you declare it by telling the compiler its name as well as what type of data it can store. Variable declaration tells the compiler to allocate appropriate memory space for the variable based on its data type. The syntax for declaring a variable is: datatype variableName; Later you will be introduced to additional data types

18 18 If variables are of the same type, they can be declared together, as follows: datatype variable1, variable2,..., variablen; The variables are separated by commas. You can declare a variable and initialize it in one step. Declaring Variables int i, j, k; // Declare i, j, and k as int variables int count = 1; int count; count = 1; int i=5, j=3, k=0 ; // note the comas and semicolon a variable must be declared and initialized before it can be used.

19 19 Assignment Statements After a variable is declared, you can assign a value to it by using an assignment statement The syntax for assignment statements is as follows: variable = expression; An expression represents a computation involving values, variables, and operators int x = 1, z; // Assign 1 to x; double radius = 1.0; // Assign 1.0 to radius; char a = 'A'; // Assign 'A' to a; int y = 5 * 10; x = y + 4; y = y + 1; 1 = x; // Wrong x=y=z=10;

20 20 Constants constant, represents permanent data that never changes (syntax as follows): final datatype CONSTANTNAME = VALUE; There are three benefits of using constants: you don’t have to repeatedly type the same value if it is used multiple times; if you have to change the constant value 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. final double PI = 3.14159;

21 21 Constants example

22 22 Numerical Data Types

23 23 Numeric Operators

24 24 Reading Numbers from the Keyboard

25 25 Integer Division +, -, *, /, and % 5 / 2 yields an integer 2. 5.0 / 2 yields a double value 2.5 5 % 2 yields 1 (the remainder of the division)

26 26 Remainder Operator Remainder is very useful in programming. For example, an even number % 2 is always 0 and an odd number % 2 is always 1. So you can use this property to determine whether a number is even or odd. Suppose today is Saturday and you and your friends are going to meet in 10 days. What day is in 10 days? You can find that day is Tuesday using the following expression:

27 27 Problem: Displaying Time Write a program that obtains hours and minutes from seconds.

28 28 Number Literals A literal is a constant value that appears directly in the program. For example, 34, 1,000,000, and 5.0 are literals in the following statements: int i = 34; long x = 1000000; double d = 5.0;

29 29 Arithmetic Expressions is translated to (3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)

30 30 How to Evaluate an Expression You can safely apply the arithmetic rule for evaluating a Java expression.

31 31 Problem: Converting Temperatures Write a program that converts a Fahrenheit degree to Celsius using the formula:

32 32 Shortcut Assignment Operators OperatorExampleEquivalent +=i += 8 i = i + 8 -=f -= 8.0f = f - 8.0 *=i *= 8 i = i * 8 /=i /= 8 i = i / 8 %=i %= 8 i = i % 8

33 33 Increment and Decrement Operators OperatorNameDescription ++varpreincrementThe expression (++var) increments var by 1 and evaluates to the new value in var after the increment. var++postincrementThe expression (var++) evaluates to the original value in var and increments var by 1. --varpredecrementThe expression (--var) decrements var by 1 and evaluates to the new value in var after the decrement. var--postdecrement The expression (var--) evaluates to the original value in var and decrements var by 1.

34 34 Increment and Decrement Operators, cont.

35 35 Increment and Decrement Operators, cont. Using increment and decrement operators makes expressions short, but it also makes them complex and difficult to read. Avoid using these operators in expressions that modify multiple variables, or the same variable for multiple times such as this: int k = ++i + i.

36 36 Assignment Expressions and Assignment Statements Prior to Java 2, all the expressions can be used as statements. Since Java 2, only the following types of expressions can be statements: variable op= expression; // Where op is +, -, *, /, or % ++variable; variable++; --variable; variable--;

37 37 Numeric Type Conversion Consider the following statements: byte i = 100; long k = i * 3 + 4; double d = i * 3.1 + k / 2;

38 38 Conversion Rules When performing a binary operation involving two operands of different types, Java automatically converts the operand based on the following rules: 1. If one of the operands is double, the other is converted into double. 2. Otherwise, if one of the operands is float, the other is converted into float. 3. Otherwise, if one of the operands is long, the other is converted into long. 4. Otherwise, both operands are converted into int.

39 39 Type Casting Implicit casting double d = 3; (type widening) Explicit casting int i = (int)3.0; (type narrowing) int i = (int)3.9; (Fraction part is truncated) What is wrong?int x = 5 / 2.0;

40 40 Problem: Keeping Two Digits After Decimal Points Write a program that displays the sales tax with two digits after the decimal point. SalesTax Run

41 41 ECE 448 – FPGA and ASIC Design with VHDL


Download ppt "1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from."

Similar presentations


Ads by Google