Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

Chapters 1 & 2 Java Programming p. 1 A) Creating a Simple Java Program B) Producing a Java Program Enter Source code: Readable English-like code written in a particular programming language...

Chapters 1 & 2 Java Programming p. 1 A) Creating a Simple Java Program B) Producing a Java Program Enter Source code: Readable English-like code written in a particular programming language Welcome.java public class Welcome { public static void main(String[] args) { // Welcome the user System.out.println("Welcome to Java!"); } // end main } // end class If no squiggly lines, run the code in Eclipse Running the program first completes a compilation phase Java source code compiler: A program that translates source code into byte code which the Java Interpreter Compiler (JVM – Java Virtual Machine) can understand. (The name of the Java program is “javac”) Byte code Welcome.class Êþº¾ 4 " Welcome java/lang/Object ()V Code LineNumberTable LocalVariableTable this LWelcome; main ([Ljava/lang/String;)V java/lang/System out Ljava/io/PrintStream; Welcome to Java! java/io/PrintStream println (Ljava/lang/String;)V args [Ljava/lang/String; SourceFile Welcome.java ! / *· ± 7 ² ¶ ± - ! Java Virtual Machine Output Welcome to Java! Note: In a language like C++, compilation does not produce byte code, rather it produces machine code that is directly understood by the computer. For JCCC students only, 1-time print permission; @Copyright, M Van Gorp Chapters 1 & 2 Java Programming p. 2 C) The Smallest Java Console Application Programs Code (minimal) public class TestClass { public static void main(String[] args) { } } Code (with initial brace on same line as code) public class TestClass { public static void main(String[] args) { } } Code (with comments and output) public class Welcome { public static void main(String[] args) { // Welcome the user System.out.println("Welcome to Java!"); } // end main } // end class What two things does every Java console application need? A __________________ of code begins with a left (opening) brace and ends with a right (closing) brace. What does void mean? What do the two forward slashes (//) represent? Everything from the ___ through the __________________________________ is ignored by the compiler. What does the represent? Everything from the opening _____ through the closing _____ is ignored by the compiler. The convention for header comments for the class and methods is to begin with ____________. Coding Style: Class documentation is placed immediately above its definition and includes the author’s name and a description of the purpose of the class (don’t describe the syntax such as class A uses a while loop…) @author first-name last-name class ClassName description of purpose… Code is aligned and indented 2 – 5 spaces in any block. A single statement within a loop, if, or else clause not containing braces is also indented and is on the line below the condition or else keyword. Braces {} either a) align vertically or b) the left brace starting each new block is on the same line as the construct it defines, and the terminating right brace lines up with the beginning of the construct. Exception: Braces on the same line are allowable if there is 80 characters) are clearly broken into separate lines. Note that a space is a character. Strive to limit methods to 25 statements or less. One can determine if a line is longer than 80 characters by clicking at the end of the line and then looking at the numbers shown at the bottom of the Eclipse editor. Theses numbers indicates the line and column position of the cursor. If a line longer than 80 characters, readability is enhanced by splitting it onto multiple lines: System.out.println("I really enjoy pets, and I have a pet named " + petName + " who is " + age + " years old."); System.out.println("I really enjoy pets, and I have a pet named " + petName + " who is " + age + " years old."); Coding Style: Additional Related Requirements for Documentation Contain correct spelling, grammar, and punctuation. Accurately describe the code. Are concise. Often use commands beginning with action verbs. A short comment describing only one line of code may be placed just to the right of the code it describes (if not surpassing 80 character per line). Other comments are placed directly above the code described, and the beginning / is aligned with the first character of code on the next line. Document lines of code where appropriate (don’t comment the obvious or restate the code). Assume the reader is computer literate and familiar with programming and the language used but knows nothing about the intent of the code. 2) Example 2 Code 01 import java.util.Scanner; 02 Note: Except for input, the variable names in 03 public class TestClass this code example are not descriptive: They 04 { merely serve to represent the data type that 05 public static void main(String[] args) is stored. Use descriptive variable names in 06 { your programs. 07 Scanner input = new Scanner(System.in); 08 09 System.out.print("Enter a number between -127 and 127: "); 10 //byte b = input.nextByte(); 11 byte b = Byte.parseByte(input.nextLine()); 12 System.out.println("Converted to byte: " + b); 13 14 System.out.print("Enter a single character: "); 15 char c = input.nextLine().charAt(0); 16 System.out.println("Converted to char: " + c); 17 18 System.out.print("Enter a line of text: "); 19 String str = input.nextLine(); 20 System.out.println("String: " + str); 21 22 System.out.print("Enter a number to convert to type short: "); 23 //short s = input.nextShort(); 24 short s = Short.parseShort(input.nextLine()); 25 System.out.println("Converted to short: " + s); For JCCC students only, 1-time print permission; @Copyright, M Van Gorp Chapters 1 & 2 Java Programming p. 17 26 27 System.out.print("Enter a number to convert to type int: "); 28 //int i = input.nextInt(); 29 int i = Integer.parseInt(input.nextLine()); 30 System.out.println("Converted to int: " + i); 31 32 System.out.print("Enter a number to convert to type long: "); 33 //long lng = input.nextLong(); 34 long lng = Long.parseLong(input.nextLine()); 35 System.out.println("Converted to long: " + lng); 36 37 System.out.print("Enter a number to convert to type float: "); 38 //float f = input.nextFloat(); 39 float f = Float.parseFloat(input.nextLine()); 40 System.out.println("Converted to float: " + f); 41 42 System.out.print("Enter a number to convert to type double: "); 43 //double d = input.nextDouble(); 44 double d = Double.parseDouble(input.nextLine()); 45 System.out.println("Converted to double: " + d); 46 input.close(); 47 } // end main 48 } // end class Output Enter a number between -127 and 127: -127 Converted to byte: -127 Enter a single character: x Converted to char: x Enter a line of text: Java keyboard input String: Java keyboard input Enter a number to convert to type short: 100 Converted to short: 100 Enter a number to convert to type int: 12345 Converted to int: 12345 Enter a number to convert to type long: 123456789 Converted to long: 123456789 Enter a number to convert to type float: 12.23 Converted to float: 12.23 Enter a number to convert to type double: 12345.98765 Converted to double: 12345.98765 Important: When retrieving keyboard input, these notes will use nextLine – the uncommented code above. This helps avoid errors produced by end of line markers when mixing string and numeric input. I) Overflow: Be careful Code 01 int num = Integer.MAX_VALUE; 02 System.out.println(num); 03 num += 1; 04 System.out.println(num); Output 2147483647 -2147483648 For JCCC students only, 1-time print permission; @Copyright, M Van Gorp Chapters 1 & 2 Java Programming p. 18 J) Formatted Output with printf 1) The pattern with a subset of format specifiers in the format string required b boolean true, false %. c character ‘x’, ‘&’ Integer for d integer 105, -4050 minimum field f floating point 12.345678 width (optional) Dot followed by e scientific notation 1.234568e+01 Postive/Negative positive integer s string “Johnson County” produces right/left for precision (optional) A format specifier is required. alignment within the width Additional special formatting Result in the format string %% % is output %n Outputs the appropriate new line character associated with the operating system (i.e. \n, \r, \r\n) Note: \n, \r, \r\n would also still work in printf, but better to use %n Note: A comma placed just after % for numeric specifiers will insert commas as thousands separators when needed. 2) Example Code 01 String school = "JCCC Cavs"; 02 int x = 123, y = -987; 03 double d = 123.45698; 04 boolean truth = true; 05 Note: When using numeric 06 System.out.printf("%d%n", x); format specifiers such as d, e, f, 07 System.out.printf("%,d%n", x * 10); a comma immediately following 08 System.out.printf("%5d%n", x); the % will produce thousands 09 System.out.printf("%-5d x %5d%n", x, y); 10 System.out.printf("%6b%n", truth); separators as needed. 11 System.out.printf("%8.2f%n", d); 12 System.out.printf("%3.1e%n", d); 13 System.out.printf("%12.5E%n", d); 14 System.out.printf("--%s--%n", school); 15 System.out.printf("%d%%%n", x); Output (One symbol per cell) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 t r u e 1. 2 e + 0 2 1. 2 3 4 5 7 E + 0 2 For JCCC students only, 1-time print permission; @Copyright, M Van Gorp Chapters 1 & 2 Java Programming p. 19 K) Operator Shortcuts 1) Compound assignment operators General Statement Condensed Form variable = variable op expression variable op= expression Technical Note: In the condensed form, variable is only evaluated once. This can make a difference in certain situations in which variable is somewhat more complex than just a simple variable name. Examples Condensed Form i = i + 2; i = i – 2; rate = rate * (price1 + price2); result = result / numScores; result = result % 2; 2) Pre-Increment/Post-increment and Pre-Decrement/Post-Decrement Operators Analyze the following two examples and their output: Example 1 Example 2 01 int count = 10; int count = 10; 02 03 count++; ++count; 04 System.out.println(count); System.out.println(count); 05 System.out.println(count++); System.out.println(++count); 06 System.out.println(count); System.out.println(count); Output Output 11 11 11 12 12 12 When considering line 5 in Example 1, was count first incremented or displayed? When considering line 5 in Example 2, was count first incremented or displayed? Based upon what was just learned, predict the output: Example 1 Example 2 01 int count = 10; int count = 10; 02 03 count--; --count; 04 System.out.println(count); System.out.println(count); 05 System.out.println(count--); System.out.println(--count); 06 System.out.println(count); System.out.println(count); Output Output Predict the output: Example 1 Example 2 01 int count = 10; int count = 10; 02 int sum = 0; int sum = 0; 03 04 sum = --count + 2; sum = count-- + 2; For JCCC students only, 1-time print permission; @Copyright, M Van Gorp Chapters 1 & 2 Java Programming p. 20 05 System.out.println(sum); System.out.println(sum); 06 System.out.println(count); System.out.println(count); Output Output Analysis: post-increment / post-decrement (x++ or x--) First ________ the value in the expression, and then ________________ or __________________ pre-increment / pre-decrement (++x or --x) First ________________ or __________________, and then ________ that value in the expression Coding Strategy: Judiciously use the increment and decrement operators. Avoid creating difficult to understand code by mixing several of these within a single statement. L) Named Constants 1) Use in place of most literal values that do not change for the duration of the program. 2) Coding style Coding Style: Names for constants and enumerated values (inside the braces) are UPPER_CASE with underscore separators. (e.g. DAYS_IN_YEAR) Named constants are used in place of numeric literals. Exceptions: {0,1,2}; output formatting; numeric literals in formulas. 3) Example Code 01 import java.util.Scanner; 02 03 public class TestClass 04 { 05 public static void main(String[] args) 06 { 07 final double STATE_TAX_RATE =.065; 08 09 // Get salary from user 10 Scanner input = new Scanner(System.in); 11 System.out.print("Please enter your salary: $"); 12 double salary = Double.parseDouble(input.nextLine()); 13 input.close(); 14 15 // Calculate income tax and display to user 16 double incomeTax = salary * STATE_TAX_RATE; 17 System.out.printf("Your tax: $%,.2f%n", incomeTax); 18 } // end main 19 } // end class Output Please enter your salary: $50000 Your tax: $3,250.00 Two advantages of using named constants instead of numeric literals (or sometimes string literals): 1. Makes code more _________________________________. 2. Changes to the value of the constant only need to occur in one ___________________. For JCCC students only, 1-time print permission; @Copyright, M Van Gorp Chapters 1 & 2 Java Programming p. 21 M) The Math Class 1) A Subset of Methods Method Description Math.abs(value) Returns the absolute value of value Math.ceil(value) Returns value rounded up to its nearest integer as a double Math.floor(value) Returns value rounded down to its nearest integer as a double Math.min(value1, value2) Returns the smaller of value1 and value2 Math.max(value1, value2) Returns the larger of value1 and value2 Math.pow(base, exp) Returns baseexp as a double Math.rint(value) Returns value rounded to its nearest integer as a double. (.5 always rounds to nearest even.) Math.round(value) Returns value rounded to its nearest integer as a double (.5 and above rounds up, else down) Math.sqrt(value) Returns the square root of value as a double 2) Examples Given intNum1 = 4, intNum2 = -3 dblNum1 = 3.4, dblNum2 = 8.5 Result Math.abs(intNum2) 3 Math.ceil(dblNum1) 4.0 Math.floor(dblNum2) 8.0 Math.max(intNum1, dblNum1) 4.0 Math.min(intNum1, dblNum1) 3.4 Math.min(intNum1, intNum2) -3 Math.pow(intNum2, intNum1) 81.0 Math.pow(3, 2.5) 15.588457268119896 Math.rint(3.49) 3.0 Math.rint(3.5) 4.0 Math.rint(3.51) 4.0 Math.rint(4.49) 4.0 Math.rint(4.5) 4.0 Math.rint(4.51) 5.0 Math.round(dblNum2) 9 Math.sqrt(intNum1) 2.0 Math.sqrt(dblNum1) 1.8439088914585775 Code 01 import java.util.Scanner; 02 public class Driver 03 { 04 public static void main(String[] args) 05 { 06 // Get the side length 07 Scanner input = new Scanner(System.in); 08 System.out.print("Unit length of cube side: "); 09 double side = Double.parseDouble(input.nextLine()); 10 input.close(); 11 12 // Display the volume 13 System.out.printf("Volume: %,.2f units%n", Math.pow(side, 3)); 14 } // end main 15 }//end class Output Length of cube side: 3.2 Volume: 32.77 units For JCCC students only, 1-time print permission; @Copyright, M Van Gorp Chapters 1 & 2 Java Programming p. 22 N) Random Numbers 1) Class and Common Methods Class Random Constructs a new Random object whose seed is based upon Random() the computer system clock when created. Constructs a new Random object whose seed is based upon Random(int seed) the value of the seed parameter. returns a random integer in the range [-231, 231 – 1] or nextInt() [-2,147,483,648, 2,147,483,647] nextInt(int upper) returns a random integer in the range [0 – upper) nextInt(int lower, int upper) returns a random integer in the range [lower – upper) 2) Examples Code 01 import java.util.Random; 02 public class TestClass 03 { 04 public static void main(String[] args) 05 { 06 final int SEED = 7; 07 final int LIMIT = 4; 08 Random randomNumbers = new Random(); 09 10 // Illustrate nextInt 11 System.out.println(randomNumbers.nextInt()); 12 System.out.println(randomNumbers.nextInt()); 13 System.out.println(randomNumbers.nextInt()); 14 15 // Illustrate nextInt with an upperbound 16 System.out.println(randomNumbers.nextInt(LIMIT)); 17 System.out.println(randomNumbers.nextInt(LIMIT)); 18 System.out.println(randomNumbers.nextInt(LIMIT)); 19 } // end main 20 }//end class Output (First Run) 2031495957 -1203270030 1105003315 2 1 3 Output (Second Run) 1250977743 -1246880425 -1217610541 1 3 0 Same code as before, but a seed constant is now used on line 08 06 final int SEED = 7; 07 final int LIMIT = 4; 08 Random randomNumbers = new Random(SEED); Output (First Run) -1156638823 -1552468968 For JCCC students only, 1-time print permission; @Copyright, M Van Gorp Chapters 1 & 2 Java Programming p. 23 -1077308326 0 1 1 Output (Second Run) -1156638823 -1552468968 -1077308326 0 1 1 Same code as before, but with a different seed 10 final int SEED = 10; 11 final int LIMIT = 4; 12 Random randomNumbers = new Random(SEED); Output (First Run) -1157793070 1913984760 1107254586 1 0 2 Output (Second Run) -1157793070 1913984760 1107254586 1 0 2 3) Generating integer values in the range [LOW, HIGH] randObject.nextInt(HIGH – LOW + 1) + LOW -- or -- randObject.nextInt(LOW, HIGH + 1) Code 01 import java.util.Random; 02 public class TestClass 03 { 04 public static void main(String[] args) 05 { 06 final int DICE_LOW = 1; 07 final int DICE_HIGH = 6; 08 Random randomNumbers = new Random(); 09 10 int face = randomNumbers.nextInt(DICE_LOW, DICE_HIGH + 1); 11 System.out.println(face); If you have an older Java version that does not allow 2 parameters to 12 } // end main be sent to Next, then the following also works: 13 }//end class int range = DICE_HIGH - DICE_LOW + 1; int face = randomNumbers.nextInt(range) + DICE_LOW; Output (First Run) 1 Output (Second Run) 3 Output (Third Run) 6 For JCCC students only, 1-time print permission; @Copyright, M Van Gorp Chapter 3 Java Programming p. 24 A) Decision Making with If Statements 1) Block Block syntax Example { public static void main(String[] args) statement1 { statement2 int num1 = 1;. int num2 = 2;. int sum = num1 + num2;. statementn System.out.println("Sum: " + sum); } } // end main 2) Relational (Comparison) Operators Relationship Tested Operator Equal to Not equal to Greater than > Less than < Greater than or equal to >= Less than or equal to = y → 5 >= (-7) → x - y < 10 → 5 - (-7) < 10 → 12 < 10 → For JCCC students only, 1-time print permission; @Copyright, M Van Gorp Chapter 3 Java Programming p. 25 4) Two selection statements: If and If-Else If Statement Syntax Example if (condition) Scanner input = new Scanner(System.in); { final int PASSING_LIMIT = 60; statement(s) } System.out.print("Please enter a numeric grade " + "with no decimal point: "); int grade = Integer.parseInt(input.nextLine()); Semantics (Meaning): If the condition is true, then execute System.out.println("You entered: " + grade); the block of statements. if (grade >= PASSING_LIMIT) Note: Braces needed when { more than one statement is in System.out.println("You passed!"); } // end if the if block, else they are... optional. If-Else Statement Syntax Example if (condition)... { if (grade >= PASSING_LIMIT) statement(s) { } System.out.println("You passed!"); else } // end if { else statement(s) { } System.out.println("Better luck next time"); } // end else Semantics: If the condition is... true, then execute the first block statements; else execute the second block of statements. Note: Braces needed when more than one statement is in the if or else blocks, else they are optional. Coding strategy: In principle, some suggest to always use braces with if statement blocks (and loops) even if only one statement is used. Why? Blocks of code are clearly outlined, and it prevents the possibility of forgetting to add braces if more statements were later added to the block. For JCCC students only, 1-time print permission; @Copyright, M Van Gorp Chapter 3 Java Programming p. 26 Warning: Placing a semicolon after the if statement condition will produce a syntax or logic error. Suppose grade currently contains the value 56: Logic Error if (grade >= PASSING_LIMIT); { System.out.println("You passed!"); } // end if Output You passed! Syntax Error if (grade >= PASSING_LIMIT); { System.out.println("You passed!"); } // end if else { System.out.println("Better luck next time"); } // end else Note: The placement of a block’s beginning brace is generally one of preference. Choose one of the formats below that suits you and stick with it. Format 1 Format 2 if (condition) if (condition) { { statement(s); statement(s); } } Blocks are easily identified, and it is easy to More code can be seen without see the paired beginning and ending scrolling. braces. Coding guidelines revisited: Coding Style: Braces {} either a) align vertically or b) the left brace starting each new block is on the same line as the construct it defines, and the terminating right brace aligns with the beginning of the construct. Exception: Braces on the same line are allowable if there is = MIN_A) statement(s); { } System.out.println("A range.");. }. else if (grade >= MIN_B). { else if (conditionn) System.out.println("B range."); { } statement(s); else if (grade >= MIN_C) } { else System.out.println("C range."); { } statement(s); else if (grade >= MIN_D) } { System.out.println("D range."); Note: The italicized final else } clause is optional. else { System.out.println("Not Passing"); }... Note: This is really just nesting if-else statements within the trailing else blocks; however, this format avoids many potential levels of indentations drifting to the right. Same solution but with rightward drift... if (grade >= MIN_A) { System.out.println("A range."); } else if (grade >= MIN_B) { System.out.println("B range."); } else if (grade >= MIN_C) { System.out.println("C range."); } else if (grade >= MIN_D) { System.out.println("D range."); } else { For JCCC students only, 1-time print permission; @Copyright, M Van Gorp Chapter 3 Java Programming p. 28 System.out.println("Not Passing"); }... 6) Nesting inside an if Code Code if (x > 0) if (x > 0) if (y > 0) { System.out.println("Quadrant I"); if (y > 0) else if (y < 0) { System.out.println("Quadrant IV"); System.out.println("Quadrant I"); } else if (y < 0) { System.out.println("Quadrant IV"); } } // end if x Warning: An else is always matched with the nearest preceding unmatched if (regardless of indentation) if (x > 0) if (y > 0) System.out.println("Quadrant I"); else if (y < 0) System.out.println("Quadrant IV"); B) Floating Point Number Comparison Looping statements will be 1) Warning: Do not use == or != to compare floating point numbers discussed in detail later. Code Code double i = 0; double i = 0; while (i < 2) while (i != 0.3) { { System.out.println(i); System.out.println(i); i +=.1 i +=.1 } } Output Output 0.0 0.0 0.1 0.1 0.2 0.2 0.30000000000000004 0.30000000000000004 0.4 0.4 0.5... (continued “infinite” output not shown) 0.6 0.7 0.7999999999999999 0.8999999999999999 0.9999999999999999 1.0999999999999999 1.2 1.3 1.4000000000000001 1.5000000000000002 1.6000000000000003 1.7000000000000004 1.8000000000000005 1.9000000000000006 For JCCC students only, 1-time print permission; @Copyright, M Van Gorp Chapter 3 Java Programming p. 29 2) Coding strategy: Consider floating point numbers equal if “close” (e.g. within.0001) to eachother Code final double EPSILON =.0001; final double TARGET = 0.3; double i = 0; while (Math.abs(i - TARGET) >= EPSILON) { System.out.println(i); i +=.1; } Output 0.0 0.1 0.2 C) Character and String Comparison 1) Remember the ASCII table (subset of Unicode): Characters are represented as integers 2) Comparing characters Note: Because we are comparing characters, you Given: can think of the value stored in response as being char response = 'y'; enclosed in single quotes – even though single What are the values of the following expressions? quotes are really not stored (The character’s ASCII value is represented in storage.). 'A' < 'B' → → response == 'y' → 'y' == 'y' → 121 == 121 → response < 'Y' → 'y' < 'Y' → 121 < → 3) Comparing strings and characters within a string a) Compare strings character by character left to right until either a mismatch is found, or the end of a string is reached. b) If a character mismatch is found the string containing the lower Unicode (ASCII) value of the two mismatched characters is less Else if the strings are of different lengths the shorter string is less Else the strings are equal Two recommended ways to perform string comparisons Purpose? methods Returns Only comparing for equality? str1.equals(str2) true if str1 equals str2, else false !str1.equals(str2) true if str1 does not equal str2, else false str1.equalsIgnoreCase(str2) Same as equals, but not case-senitive. Determining sorted order str1.compareTo(str2) < 0 if str1 < str2, 0 if str1 equals str2, > 0 if str1 > str2 str1.compareToIgnoreCase(str2) Same as compareTo, but not case-senstive For JCCC students only, 1-time print permission; @Copyright, M Van Gorp Chapter 3 Java Programming p. 30 Examples Given: String mascot = "Chief"; Expression Mismatch? Returns "KU".equals("JCCC") Yes false "KU".compareTo("JCCC") K=75, J=74 1 "Olathe East".equals("Olathe NW") Yes false "Olathe East".compareTo("Olathe NW") E=69, N=78 -9 mascot.equals("Chiefs") No false mascot.compareTo("Chiefs") No -1 mascot.equals("Chief") No true mascot.compareTo("Chief") No 0 "KState".equals("KSTATE") Yes false "KState".equalsIgnoreCase("KSTATE") No true "KState".compareTo("KSTATE") t=116, T=84 32 In the context of an if statement: Code 01 String mascot = "Chief"; 02 String mascot2 = new String("Chief"); 03 Warning: do not 04 if (mascot == "Chief") use relational 05 System.out.println("mascot == \"Chief\""); operators such as 06 == to compare 07 if (mascot.equals(mascot2)) strings. Why? 08 System.out.println("mascot.equals(mascot2)"); 09 10 if (mascot.equals("Chief")) 11 System.out.println("mascot.equals(\"Chief\")"); 12 13 if (mascot == mascot2) 14 System.out.println("mascot == mascot2"); 15 16 if ("KU".compareTo("JCCC") > 0) 17 System.out.println("KU is alphabetically after JCCC"); Output mascot == "Chief" mascot.equals(mascot2) mascot.equals("Chief") KU is alphabetically after JCCC c) Accessing characters in a string Code 01 Scanner input = new Scanner(System.in); 02 03 String state = "Kansas"; 04 if(state.charAt(0) == 'K') 05 { 06 System.out.println("The state begins with a K"); 07 } 08 if(state.charAt(state.length() - 1) == 's') 09 { 10 System.out.println("The state ends with an s"); For JCCC students only, 1-time print permission; @Copyright, M Van Gorp Chapter 3 Java Programming p. 31 11 } 12 13 System.out.print("Continue? (Y or N): "); 14 char again = input.nextLine().toUpperCase().charAt(0); 15 if (again == 'Y') 16 System.out.println("Run again"); Output (First run) The state begins with a K The state ends with an s Continue? (Y or N): y Run again Output (Second run) The state begins with a K The state ends with an s Continue? (Y or N): N D) Logical Operators: Advanced Decision Making with Compound Conditions 1) Introduction and Examples English Java Logical Operator Semantics Both expressions must be true for the And result to be true. One of the two expressions must be true Or for the result to be true. Changes a true condition to false and vice Not versa. Short circuit evaluation: Once it can be Given: determined that the entire condition is int score1 = 5; true or false, the rest of the condition is int score2 = 3; not evaluated. Thus, score2 > score3 int score3 = -1; would not even be evaluated below. char response = 'Y'; score1 < score2 score1 < score2 && score2 > score3 5 < 3 5 < 3 && 3 > (-1) F F && T F score1 < score2 || score2 > score3 !(score1 (-1) !( 5 1 does not need evaluation. response == 'y' || response == 'Y' score2 > 0 || score3 > 1 ('Y') == 'y' || ('Y') == 'Y' 3 > 0 || (-1) > 1 F || T T || F T T For JCCC students only, 1-time print permission; @Copyright, M Van Gorp Chapter 3 Java Programming p. 32 Suppose y is an integer containing 0, x is a float containing 10.0, and RATIO is a constant holding some number. Why would the following code not produce a division by 0 error? if (y > 0 && x / y < RATIO) { System.out.println (x / y); } Warning: A compound condition in programming is different from other written or spoken representations. Error Error Correct if (x < y < z) if (x < y && < z) if (x < y && y < z)......... 2) Operator precedence also makes a difference a) Updated precedence table: Precedence Operators Associativity Examples Highest ( ) left to right x * (4 + z) var++, var-- left to right count++ unary + unary -, right to left -4, -8, +2, --count, ++var, --var, !(x < y), (int)x / y ! (type) * / % left to right x / 2 * y % z + - left to right x + y - z < > = left to right x 10) Lowest || left to right (x < y) || (y > 10) ?: right to left (x < y) ? x : y; =, +=, -=, right to left x = 5 – 2 * 3; *=, /=, %= count -= 2; b) A longer example using the precedence table above. !(score1 < score2) || score2 > score3 && score3 > score1 First, substitute in all the values !(5 < 3) || 3 > (-1) && (-1) > 5 For JCCC students only, 1-time print permission; @Copyright, M Van Gorp Chapter 3 Java Programming p. 33 E) Simplifying Negation -- De Morgan’s laws 1) The laws: The Laws Negation effects (opposite) !(expr1 && expr2) → !(expr1) || !(expr2) || && !(expr1 || expr2) → !(expr1) && !(expr2) != == < >= > d) && x > y ) 3) Sample code with a compound condition Code 01 final int LOWER = 0, UPPER = 10; 02 03 // Get the number 04 Scanner input = new Scanner (System.in); 05 System.out.print("Please guess a number between " + 06 LOWER + " and " + UPPER + " inclusively: "); 07 int guess = Integer.parseInt(input.nextLine()); 08 input.close(); 09 Using De Morgan’s Laws, this could also be 10 // Check the range written as: 11 if ( !(guess >= LOWER && guess UPPER) 12 { 13 System.out.println("I'm sorry, you entered an invalid number."); 14 } Output Please guess a number between 0 and 10 inclusively: 11 I'm sorry, you entered an invalid number. Output Please guess a number between 0 and 10 inclusively: 5 F) The conditional operator (ternary operator) 1) Syntax General Format Semantics booleanExpr ? value1 : value2; If booleanExpr evaluates to true, the result of the entire expression is value1, else the result is value2. 2) Examples If-else statement if (grade >= PASS_LIMIT) message = "Passing"; else message = "Not Passing"; Equivalent statement message = ((grade >= PASS_LIMIT) ? "Passing" : "Not Passing"); For JCCC students only, 1-time print permission; @Copyright, M Van Gorp Chapter 3 Java Programming p. 34 If-else statement if (grade >= PASS_LIMIT) System.out.println("Passing"); else System.out.println("Not Passing"); Equivalent statement System.out.println((grade >= PASS_LIMIT) ? "Passing" : "Not Passing"); G) Switch statement: A third type of selection statement (in addition to if, if-else) 1) Syntax and semantics Common Format Semantics switch (expression) Execute the statements associated { with the case constant that matches case constant-1: the value produced by expression. statement(s); break; Continue executing all statements case constant-2: until a break or the end of the switch statement(s); statement is reached. (Not all cases break; require a break.).. If there is no match and a default. case exists, the statements case constant-n: statement(s); associated with the default case are break; executed. default: statement(s); If a case constant is matched that has break; no associated statements or a break, } control transfers to the next case. Key points: The switch expression must evaluate to a char, byte, short, int, or String type. The italicized default case is optional. It is just like the optional else in an if-else statement. For JCCC students only, 1-time print permission; @Copyright, M Van Gorp Chapter 3 Java Programming p. 35 2) Examples a) Example 1 Code 01 int grade = 78; 02 03 switch (grade / 10) 04 { 05 case 9: 06 System.out.println("A"); 07 break; 08 case 8: 09 System.out.println("B"); 10 break; 11 case 7: 12 System.out.println("C"); 13 break; 14 case 6: 15 System.out.println("D"); 16 break; 17 default: 18 System.out.println("F"); 19 break; 20 } // end switch Output (One symbol per cell; Assume tabs insert 3 spaces) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 What if grade initially contained the value 34? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 What if grade initially contained the value 100? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 A fix for a grade of 100 Code 01 int grade = 78; 02 03 switch (grade / 10) 04 { 05 case 10: 06 case 9: 07 System.out.println("A"); 08 break; 09 case 8: 10 System.out.println("B"); 11 break;... For JCCC students only, 1-time print permission; @Copyright, M Van Gorp Chapter 3 Java Programming p. 36 b) Example 2 Code 01 String strGrade = "B"; 02 03 switch (strGrade) 04 { 05 case "A": 06 System.out.println("90's or above."); 07 break; 08 case "B": 09 System.out.println("80's"); 10 break; 11 case "C": 12 System.out.println("70's"); 13 break; 14 case "D": 15 System.out.println("60's"); 16 break; 17 case "F": 18 System.out.println("Below 60."); 19 break; 20 } // End switch Output (One symbol per cell; Assume tabs insert 3 spaces) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 What if strGrade initially contained "a"? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 What if strGrade initially contained "A" and lines 07 and 10 were removed? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 For JCCC students only, 1-time print permission; @Copyright, M Van Gorp Chapter 4 Java Programming p. 37 A) Repetition Statements 1) Suppose we need to compute tax for 3 different salaries Code 01 import java.util.Scanner; 02 03 public class TaxComputation 04 { 05 public static void main(String[] args) 06 { 07 final double STATE_TAX_RATE =.065; 08 09 // Get salary from user 10 Scanner input = new Scanner(System.in); 11 System.out.print("Please enter a salary: $"); 12 double salary = Double.parseDouble(input.nextLine()); 13 14 // Calculate income tax and display to user 15 double incomeTax = salary * STATE_TAX_RATE; 16 System.out.printf("Your tax: $%,.2f%n", incomeTax); 17 18 // Get another salary from user 19 System.out.print("Please enter a salary: $"); 20 salary = Double.parseDouble(input.nextLine()); 21 22 // Calculate income tax and display to user 23 incomeTax = salary * STATE_TAX_RATE; 24 System.out.printf("Your tax: $%,.2f%n", incomeTax); 25 26 // Get another salary from user 27 System.out.print("Please enter a salary: $"); 28 salary = Double.parseDouble(input.nextLine()); 29 30 // Calculate income tax and display to user 31 incomeTax = salary * STATE_TAX_RATE; 32 System.out.printf("Your tax: $%,.2f%n", incomeTax); 33 34 input.close(); 35 } // end main 36 } // end class Output Please enter a salary: $50000 Your tax: $3,250.00 Please enter a salary: $45500 Your tax: $2,957.50 Please enter a salary: $39250 Your tax: $2,551.25 What if we need to enter 100 salaries? What if we didn’t know how many salaries were to be entered? For JCCC students only, 1-time print permission; @Copyright, M Van Gorp Chapter 4 Java Programming p. 38 Note 1: The BigDecimal class (java.math.BigDecimal) can be used in place of double to represent money Note 2: The DecimalFormat class (java.text.DecimalFormat) can be used to format numbers as money Code 01 import java.util.Scanner; 02 import java.text.DecimalFormat; 03 04 public class TestClass 05 { 06 public static void main(String[] args) 07 { 08 final double STATE_TAX_RATE =.065; 09 10 // Get salary from user 11 Scanner input = new Scanner(System.in); 12 System.out.print("Please enter a salary: $"); 13 double salary = Double.parseDouble(input.nextLine()); 14 input.close(); 15 16 // Calculate income tax and display to user 17 double incomeTax = salary * STATE_TAX_RATE; 18 DecimalFormat currencyFormat = new DecimalFormat("$#,##0.00"); 19 System.out.printf("Your tax: %s%n", 20 currencyFormat.format(incomeTax)); 21 } // end main 22 } // end class Output Please enter a salary: $47525 Your tax: $3,089.12 2) While statement a) Visualization and Semantics Flow Chart Semantics If the condition is true, execute the statements inside the loop body. Then, return to test the loop condition. F condition If the condition is still true, again execute the statements inside the loop body. T Eventually, when the condition becomes false, jump to the next statement after the (loop body) loop body. statement(s) b) Syntax General Syntax while (condition) { statement(s); } Note: braces are optional if only one statement in the loop body. For JCCC students only, 1-time print permission; @Copyright, M Van Gorp Chapter 4 Java Programming p. 39 c) Counter-controlled while loops Code Variable Trace final int LIMIT = 3; int i = 1; i: while (i

Use Quizgecko on...
Browser
Browser