Download presentation
Presentation is loading. Please wait.
Published by麦晓 汪 Modified over 5 years ago
1
CS2011 Introduction to Programming I Elementary Programming
Chengyu Sun California State University, Los Angeles
2
Overview Variables and Constants More operators
Data types More operators And Math.pow() More about literals (i.e. values) Type mismatch and conversion Input using Scanner Put everything together
3
Example: Circle Measurements
Write a program that displays the diameter, perimeter, and area of a circle that has a radius of 6.5
4
CircleMeasurements.java public class CircleMeasurements {
public static void main(String args[]) { System.out.println("Diameter is " * 2); System.out.println("Perimeter is " + 2 * * 6.5); System.out.println("Area is " * 6.5 * 6.5); }
5
Problem with CircleMeasurements.java
public class CircleMeasurements { public static void main(String args[]) { System.out.println("Diameter is " * 2); System.out.println("Perimeter is " + 2 * * 6.5); System.out.println("Area is " * 6.5 * 6.5); } Repeating the same value multiple times is bad Tedious to type Easy to make mistake (i.e. typo)
6
Use a Variable double radius = 6.5;
Type Variable Name Variable Value double radius = 6.5; System.out.println("Diameter is " + 2*radius); System.out.println("Perimeter is " + 2* * radius); System.out.println("Area is " * radius*radius);
7
Why Repeating Variables Is Better
Variable name is more descriptive, which makes the code more readable, thereby easier to understand and debug Variable is more reusable, e.g. set radius to a different value and use the same formula Compiler/IDE can help finding typos
8
Create A Variable double radius = 6.5; double radius; radius = 6.5;
// Declare a variable // Assign a value to a variable Variables can be declared anywhere in a method A variable can only be used after it’s declared
9
Variable Declaration double radius; Data Type Name Computer Memory
Compiler allocates a space in computer memory based on the size required by the data type Name will be used to refer to whatever value stored in the space
10
Data Types in Java Primitive types Class types
E.g. int, float, double, boolean Type name starts with a lowercase letter Class types E.g. String Type name starts with a uppercase letter
11
Primitive Numerical Types
Name Range Size byte -27 to 27-1 1 byte short -215 to 215-1 2 bytes int -231 to 231-1 4 bytes long -263 to 263-1 8 bytes float Very large double For integer numbers like -2, 100 For numbers with a fraction, e.g. -2.5, When unsure, use int and double
12
About float and double float: single-precision floating point numbers
double: double-precision floating point numbers Because they use limited storage space to represent infinite possible values, some values may not be represented exactly (though usually they are accurate enough) double is more accurate than float
13
Assignment Statement radius = 6.5;
Assignment operator Assign the value on the right to the variable on the left Right-hand side can be an expression = is assignment, not equals
14
Some Other Forms of Variable Declaration/Assignment
int a, b, c, d; double x, y=2.5, z; a = b = c = 10; d = a + b + c; Assignment operator = is right associative (i.e. evaluates from right to left) Arithmetic operators like + are left associative (i.e. evaluates from left to right)
15
Constant final double PI = 3.14159;
A constant is basically a variable whose value cannot be changed Usually used to represent some value that should remain unchanged throughout a program Naming convention All capital letters Use _ to concatenate multiple words
16
More About Numerical Operators
+, -, *, / + is also used for string concatenation The remainder (a.k.a. modulus) operator % The result is the remainder (i.e. the amount left over) after a division, e.g. 9%2=1 Example: PrintDigits.java
17
Associativity and Precedence
Precedence determines the order of evaluation of different operators Associativity determines the order of evaluation of operators with the same precedence For example, what's the result of the following expression?? 1 + 2 * * 5 % 6 - 7
18
Convenience Operators …
Certain operations are used so often that they get their own operators Use the value of a variable, does some calculation, then assign the result back to the variable Increment and decrement by 1
19
… Convenience Operators
n = n + 10 n = n – 10 n = n * 10 n = n / 10 n = n % 10 n += 10 n -= 10 n *= 10 n /= 10 n %= 10 ++n n++ Pre-increment n = n + 1 Post-increment --n n-- Pre-decrement n = n - 1 Post-decrement
20
Exercise: Pre/Post Increment/Decrement
int a = 1, b = 1; int c1 = a * 10; int c2 = 10 + b++ * 10; a = b = 1; c1 = a * 10; c2 = 10 + b-- * 10;
21
Math.pow(x,y) It is a method, not an operator
Used for calculating x to the power of y For example: 23 Math.pow(2,3) 8
22
Types of Literals "Welcome to Java!" String 10
byte, short, int, or long ?? 10.5 float or double??
23
Other Forms of Literals
Type Notes 10l or 10L long 10.5f or 10.5F float 1.1e2 or 1.1E2 double scientific notation 10 int decimal (i.e. base 10) 0b10 or 0B10 binary (i.e. base 2) 0710 octal (i.e. base 8) 0x10 or 0X10 hexadecimal (i.e. base 16)
24
Type Mismatch short a; int b; float c; double d; a = 1000000; // ??
25
Type Mismatch short a; int b; float c; double d;
a = ; // error. overflow b = ; // ok c = ; // ok d = ; // ok a = 3.6; // error. Loss of data b = 3.6; // error. Loss of data c = 3.6; // error. Loss of precision d = 3.6; // ok
26
Implicit Type Conversion
A.K.A. Coercion Happens when converting a type with a smaller range to a type with a larger range, e.g. short int int long float double
27
Explicit Type Conversion
A.K.A. Casting Needed when converting a type with a larger range to a type with a smaller range Must be explicitly specified by the programmer, e.g. int n = (int) 3.6;
28
Result Types When Mixing Types in an Expression
"The result is " ?? "The result is " + (10 + 2) ?? 10 / 3 * 3 ?? 10.0 / 3 * 3 ?? 10 / 3.0 * 3 ?? 10 / 3 * 3.0 ??
29
Circle Measurements with Input
Modify the Circle Measurements example so that it lets a user to enter the value of the radius
30
Console Output and Input
System.out Console output System.in Console input Unfortunately, unlike System.out which has convenient methods like println(), System.in is pretty difficult to use
31
Use Scanner So the common practice is use a Scanner to wrap around System.in Type Variable Create a new scanner Scanner in = new Scanner( System.in ); // Read user input ... // Close the scanner in.close();
32
About Import Scanner is a not class included by the compiler by default, so it has to be imported: import java.util.Scanner; It's easy to let Eclipse do the import Click on the light bulb next to the error mark
33
Commonly Used Methods in Scanner
nextByte() nextShort() nextInt() nextLong() nextFloat() nextDouble() nextLine() Use Eclipse's autocomplete function
34
Example: Compute Average
Read three values from console and output the average
35
So Where Are We? Comments Project Packages Classes Variables Methods
Statements Statements Expressions Literals Variables Operators
36
Put Everything Together – Mortgage Calculator
See the mortgage calculator at bankrate.com Given Home price Down payment percentage Mortgage term (in years) Annual interests rate Display monthly payment
37
How Do We Do It? Find the monthly payment formula (or in Computer Science terms, the algorithm) Outline the steps in comments (i.e. pseudo-code) Implement each step Verify the result (i.e. test and debug)
38
Readings Chapter 2 of the textbook (there will be a quiz next week)
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.