CS2011 Introduction to Programming I Elementary Programming Chengyu Sun California State University, Los Angeles
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
Example: Circle Measurements Write a program that displays the diameter, perimeter, and area of a circle that has a radius of 6.5
CircleMeasurements.java public class CircleMeasurements { public static void main(String args[]) { System.out.println("Diameter is " + 6.5 * 2); System.out.println("Perimeter is " + 2 * 3.14159 * 6.5); System.out.println("Area is " + 3.14159 * 6.5 * 6.5); }
Problem with CircleMeasurements.java public class CircleMeasurements { public static void main(String args[]) { System.out.println("Diameter is " + 6.5 * 2); System.out.println("Perimeter is " + 2 * 3.14159 * 6.5); System.out.println("Area is " + 3.14159 * 6.5 * 6.5); } Repeating the same value multiple times is bad Tedious to type Easy to make mistake (i.e. typo)
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*3.14159 * radius); System.out.println("Area is " + 3.14159* radius*radius);
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
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
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
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
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, 3.1415 When unsure, use int and double
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
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
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)
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
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
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 * 3 + 4 * 5 % 6 - 7
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
… 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
Exercise: Pre/Post Increment/Decrement int a = 1, b = 1; int c1 = 10 + ++a * 10; int c2 = 10 + b++ * 10; a = b = 1; c1 = 10 + --a * 10; c2 = 10 + b-- * 10;
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
Types of Literals "Welcome to Java!" String 10 byte, short, int, or long ?? 10.5 float or double??
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)
Type Mismatch short a; int b; float c; double d; a = 1000000; // ??
Type Mismatch short a; int b; float c; double d; a = 1000000; // error. overflow b = 1000000; // ok c = 1000000; // ok d = 1000000; // 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
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
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;
Result Types When Mixing Types in an Expression "The result is " + 10 + 2 ?? "The result is " + (10 + 2) ?? 10 / 3 * 3 ?? 10.0 / 3 * 3 ?? 10 / 3.0 * 3 ?? 10 / 3 * 3.0 ??
Circle Measurements with Input Modify the Circle Measurements example so that it lets a user to enter the value of the radius
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
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();
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
Commonly Used Methods in Scanner nextByte() nextShort() nextInt() nextLong() nextFloat() nextDouble() nextLine() Use Eclipse's autocomplete function
Example: Compute Average Read three values from console and output the average
So Where Are We? Comments Project Packages Classes Variables Methods Statements Statements Expressions Literals Variables Operators
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
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)
Readings Chapter 2 of the textbook (there will be a quiz next week)