1 / 40

Chapter 2 Elementary Programming

Chapter 2 Elementary Programming. Motivations.

naoko
Download Presentation

Chapter 2 Elementary Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 2 Elementary Programming

  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. 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. 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. animation Trace a Program Execution declaring variables 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); } } memory radius no value area no value allocate memory for radius and area Java provides simple (primitive) data types for representing integers, real numbers, characters, and Boolean types.

  6. animation Trace a Program Execution assign 20 to radius 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); } } radius 20 area no value

  7. animation Trace a Program Execution memory 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); } } radius 20 area 1256.636 compute area and assign it to variable area

  8. animation Trace a Program Execution memory 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); } } radius 20 area 1256.636 print a message to the console

  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 ComputeAverage Run Run

  10. 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. 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, ornull. (they are reserved words) • An identifier can be of any length. • Use descriptive names

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

  13. 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);

  14. Declaring Variables • 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 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;

  15. Declaring Variables • 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. inti, j, k; // Declare i, j, and k as int variables intcount; count = 1; int count = 1; inti=5 , j=3 , k=0 ; // note the comas and semicolon a variable must be declared and initialized before it can be used.

  16. 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;

  17. Constants final double PI = 3.14159; • 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.

  18. Constants example

  19. Numerical Data Types

  20. Numeric Operators

  21. Reading Numbers from the Keyboard

  22. 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)

  23. 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:

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

  25. 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: inti = 34; long x = 1000000; double d = 5.0;

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

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

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

  29. Shortcut Assignment Operators Operator Example Equivalent += i += 8i= i + 8 -= f -= 8.0 f = f - 8.0 *= i *= 8i= i * 8 /= i /= 8 i = i / 8 %= i %= 8i= i % 8

  30. Increment and Decrement Operators Operator Name Description ++varpreincrement The expression (++var) increments var by 1 and evaluates to the new value in varafter the increment. var++postincrement The expression (var++) evaluates to the original value in var and increments var by 1. --varpredecrement The expression (--var) decrements var by 1 and evaluates to the new value in varafter the decrement. var--postdecrement The expression (var--) evaluates to the original value in var and decrements var by 1.

  31. Increment and Decrement Operators, cont.

  32. 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: intk = ++i + i.

  33. 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--;

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

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

  36. 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;

  37. ECE 448 – FPGA and ASIC Design with VHDL

More Related