Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
CS 201 Lecture 3: John Hurley Cal State LA Keep Up With The Reading! Future quizzes will test you on material that is in the textbook but not in the lectures. Be sure to read and understand the chapters listed in the website for this week. 2 Reserved Words Reserved words or keywords are words that have specific meanings to the compiler and cannot be used for other purposes in the program. For example, when the compiler sees the word class, it understands that the word after class is the name for the class. Some other reserved words include public, private, static, and void. Their use will be introduced later. Don’t use them as names for variables or classes. 3 Assignments radius = 1 is an assignment that sets radius to the value 1 To the computer, this means “go find the memory you set aside to keep track of radius and replace the value there with 1” radius == 1 is a test that is true if radius is equal to 1, otherwise false. Usually used in a expression like if(radius == 1) System.out.println(“radius is equal to 1!”); 4 More Fun With Data Types boolean Value that is either true or false inequalities and tests in loop statements evaluate to boolean values 1 < 2 is true, so 2 < 1 is false 2 == 2 is true int i = 2; System.out.println(i + " < " + 5 + " ? " + (i < 5)); prints "2 < 5 ? true" 5 More Fun With Data Types package demos; public class BooleanDemo { public static void main(String[] args) { int i = 1; System.out.println(i + " < " + 5 + "? " + (i < 5)); System.out.println(i + " == " + 5 + "? " + (i == 5)); System.out.println(i + " > " + 5 + "? " + (i > 5) + "\n"); i = 5; System.out.println(i + " < " + 5 + "? " + (i < 5)); System.out.println(i + " == " + 5 + "? " + (i == 5)); System.out.println(i + " > " + 5 + "? " + (i > 5) + "\n"); i = 6; System.out.println(i + " < " + 5 + "? " + (i < 5)); System.out.println(i + " == " + 5 + "? " + (i == 5)); System.out.println(i + " > " + 5 + "? " + (i > 5) + "\n"); System.out.println("(1 == 1) == (2 == 1)? " + ((1 == 1) == (2 == 1))); System.out.println("(1 < 2) == (2 < 3)? " + ((1 < 2) == (2 < 3))); } } 6 More Fun With Data Types char One character Set value using single quotes: char myChar = 'A'; ‘A’ is not the same as ‘a’ 7 More Fun With Data Types String Sequence of zero or more characters. Note the capital S String is a class; we will learn what that means later. Set values using double quotes: String myString = “Get your own String, This one is mine.” “” is called a null String or empty String. 8 Math Operations Java's math operations are easy to understand x = 1; // sets x to 1 x = x + 1; // adds 1 to x x = x * y; // multiplies x by y x = 100.0/9.2; // x should be a floating point // type, not an integer x = y + 100; 9 Math Operations: Modulo Modulo may be unfamiliar. It performs integer division and yields the remainder. The modulo operator is the symbol % x = y % 3; means "divide y by 3, ignore the quotient, and assign the remainder as the new value of x." y should be an integer. Modulo has many uses. The simplest one is that it tells us whether an integer is evenly divisible by another integer. If, for example a % b == 0, then a is evenly divisible by b. 9 % 3 is 0 10 % 3 is 1 10 Math Operations and Data Type What will the output from this code be? public class Mathematician{ public static void main(String[] args){ int total = 5; int divisor = 4; int result = total / divisor; System.out.println( total + "/" +divisor + " = " + result); } } 11 Math Operations and Data Type What about this one? public class Mathematician{ public static void main(String[] args){ int total = 5; int divisor = 3; int result = total / divisor; System.out.println( total + "/" +divisor + " = " + result); } } 12 Math Operations and Data Type This one still doesn’t work! public class Mathematician{ public static void main(String[] args){ int total = 5; int divisor = 4; double result = total / divisor; System.out.println( total + "/" +divisor + " = " + result); } } 13 Math Operations and Data Type To get a floating point result from division, you must make at least one of the operands a floating point type: public class Mathematician{ public static void main(String[] args){ int total = 5; double divisor = 4; double result = total / divisor; System.out.println( total + "/" +divisor + " = " + result); } } 14 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. * In this case binary means “involving two operands,” not “ in base 2” 15 Casting Casting converts data types You should rarely have to do this at this point For primitive types, the syntax looks like this: int x = (int) 5.1; Casting a floating point type to an integer truncates, doesn’t round! int x = (int) 1.6; 16 sets x to 1, not 2! Casting Casting the value back to the original type does not restore lost data, so if you need the original value, go back to the original variable public class Caster{ public static void main(String[] args){ double x = 1.6; int y = (int) x; System.out.println(x); System.out.println(y); System.out.println((double) y); System.out.println(x); } } outputs: 1.6 1 1.0 1.6 17 Constants Suppose you are writing a program which can calculate the circumference of a circle: 2πr the area of a circle: πr2 the volume of a cylinder: πr2h You could type in a value of pi each time you will use it 18 double radius = 5.1; double height = 3; … double circumference = 2 * 3.14 * radius; … double area = 3.14 * radius * radius; … double volume = 3.14 * radius * radius * height; Constants Better idea: define a constant and set its value once Less risk of errors or inconsistencies Clearer code; it’s easier to recognize the constant name than the value Easier to change precision Used 3.14 before for simplicity, but results were not accurate enough. Now you want to use 3.14159 19 Constants Use all caps for constant names Use final keyword final double PI = 3.14159; … code omitted… double circumference = 2 * PI * radius; 20 Combining Operations Just as in arithmetic and algebra, you can combine simple operations into complex calculations of any length public class Converter{ public static void main(String[] args){ double celsius; double fahrenheit = 212; celsius = (fahrenheit -32) * 5.0/9; System.out.println(fahrenheit + " degrees F = " + celsius + " degrees C"); } Operator Precedence 3 + 4 * 4 + 5 * (4 + 3) - 1 3 + 4 * 4 + 5 * 7 – 1 3 + 16 + 5 * 7 – 1 (1) inside parentheses first (2) multiplication (3) multiplication 3 + 16 + 35 – 1 19 + 35 – 1 54 - 1 53 22 (4) addition (5) addition (6) subtraction Combining Operations Problem: In Alphabet City, people measure horseshoes in bumps, while in Barrytown horseshoes are measured in dots. Alphabet City horseshoe sizes start with 0, while Barrytown horseshoe sizes start with 1, and Alphabet City size 0 is the same size as Barrytown size 1. 1 bump equals 0.5 dots. Thus, for example: Alphabet City size 0 = Barrytown size 1 Alphabet City size 1 = Barrytown size 1.5 Alphabet City size 4 = Barrytown size 3 Write code that converts an Alphabet City horseshoe size to a Barrytown horseshoe size 23 Combining Operations public class Demo { public static final double BUMPSTODOTS = 0.5; public static final int ALPHTOBARRY = 1; public static void main(String[] args) { double size0 = 0; double size1 = 1; double size4 = 4; double barrySize; barrySize = size0 * BUMPSTODOTS + ALPHTOBARRY; System.out.println("Alphabet City size " + size0 + " = Barrytown size " + barrySize); barrySize = size1 * BUMPSTODOTS + ALPHTOBARRY; System.out.println("Alphabet City size " + size1 + " = Barrytown size " + barrySize); barrySize = size4 * BUMPSTODOTS + ALPHTOBARRY; System.out.println("Alphabet City size " + size4 + " = Barrytown size " + barrySize); } } 24 Operator Associativity Binary operators are those that take two operands. Example: a - b All binary operators except assignment operators are left-associative. a – b + c – d is equivalent to ((a – b) + c) – d Assignment operators are right-associative. Therefore, the expression a = b += c = 5 is equivalent to a = (b += (c = 5)) x = 1 x = 10 * b; 25 Formatting Output Use the printf statement. System.out.printf(format, items); Where format is a string that may consist of substrings and format specifiers. A format specifier specifies how an item should be displayed. An item may be a numeric value, character, boolean value, or a string. Each specifier begins with a percent sign. 26 Frequently-Used Specifiers Specifier Output Example %b true or false a boolean value %c a character 'a' %d a decimal integer 200 %f a floating-point number 45.460000 %e a number in standard scientific notation %s a string 4.556000e+01 "Java is cool" int count = 5; items double amount = 45.56; System.out.printf("count is %d and amount is %f", count, amount); display 27 count is 5 and amount is 45.560000 Printf public class PrintfDemo{ public static void main(String[] args){ int intVar = 1; double doubleVar = 3.14159; double moonRadius = 1737000; // in meters char charVar = 'a'; String stringVar = "Hi, Mom"; boolean boolVar = true; System.out.printf("\nintVar: %d; \ndoubleVar: %f; \ndoubleVar to 4 places: %7.4f; \nmoonRadius: %e; \ncharVar: %c; \nstringVar: %s", intVar, doubleVar, doubleVar, moonRadius, charVar, stringVar); } // end main() } // end class Naming Conventions Choose meaningful and descriptive names. Variables and method names: Use lowercase. If the name consists of several words, concatenate all in one, use lowercase for the first word, and capitalize the first letter of each subsequent word in the name. For example, the variables radius and area, and the method computeAreaInSqCm(). 29 Naming Conventions, cont. Class names: Capitalize the first letter of each word in the name. For example, the class name ComputeArea. Constants: Capitalize all letters in constants. Use underscores to connect words or just run words together. For example, the constant PI and MAX_VALUE or MAXVALUE 30 Command Line Input There are several ways to get input from a command line In production, you will usually write programs that use GUIs, not command line I/O In school most programming classes focus on functionality, not user interface, so you need to know how to use command line I/O Command Line Input The simplest command line input class is Scanner import java.util.Scanner; Scanner has a variety of methods to get input of different data types Scanner Input Methods We describe methods using in this format: Class.method() If there are any parameters, their type goes inside the parentheses You have already seen System.out.println(String) You will often replace the class name with the name of an instance of the class: Scanner input = new Scanner(System.in); … stuff deleted… name = input.next(); In the example above, input is an instance of Scanner. We set up a Scanner and called it input! Scanner Input Methods Scanner.next() reads the next parsable String Scanner.nextLine() reads up to the next line break and puts the result in a String Scanner.nextDouble() reads the next parseable string and tries to convert it to a Double double d = Scanner.nextDouble(); There are equivalent methods for nextInteger(), nextBoolean(), etc. Scanner.next Example package demos; import java.util.Scanner; public class InputDemo { public static void main(String[] args) { Scanner input = new Scanner(System.in); String name = null; System.out.println("What is your name?"); name = input.next(); System.out.println("Nice to meet you, " + name); } } Scanner.nextDouble Example Scanner input = new Scanner(System.in); double myDouble = 0.0; System.out.print("Input a double:"); myDouble = input.nextDouble(); System.out.println("\nYou entered: " + myDouble); This joke is from Philogelos, the oldest known book of jokes, probably compiled around 300 AD: A poor student went swimming and almost drowned. Now he swears he will never go in the water again until he learns to swim