1 / 32

OLD BUSINESS : Go over homework -- 5.1 –do Show & Tell NEW BUSINESS: Following the lecture notes. Do some interestin

Class 12 Oct 07. OLD BUSINESS : Go over homework -- 5.1 –do Show & Tell NEW BUSINESS: Following the lecture notes. Do some interesting examples For Next Time: Code Wars!! Assignment for next time . For Class 13 On Oct 14. Assignment for next time.

huslu
Télécharger la présentation

OLD BUSINESS : Go over homework -- 5.1 –do Show & Tell NEW BUSINESS: Following the lecture notes. Do some interestin

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. Class 12 Oct 07 OLD BUSINESS: Go over homework -- 5.1 –do Show & Tell NEW BUSINESS: Following the lecture notes. Do some interesting examples For Next Time: Code Wars!! Assignment for next time

  2. For Class 13 On Oct 14 Assignment for next time. Do Problems PP5.8 and PP5.13 on page 287. PP5.8 is a problem about playing a Hi-Lo guessing game. (Note this requires use of random numbers – you can see these in use on page 125 – 127. (Also in the example program on slide 14.) A “sentinel value” means using something like “-1” as user input to indicate you want to quit. PP5.13 is about printing out patterns of stars. Start with the program on page 258 and understand what it is doing. Please JSubmit it to me by 11:59PM Wednesday.

  3. Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion If  brought in from Section 5.2 Interactive Programs Graphics Applets Drawing Shapes 4

  4. Flow of Control Unless specified otherwise, the order of statement execution through a method is linear: one statement after another The program can decide: to execute a particular statement – or not To execute a statement over and over Decisions are based on boolean expressions (or conditions) that evaluate to true or false. The order of statement execution is called the flow of control The Java conditional statements for now are: if statement if-else statement 5-5

  5. The if Statement The if statement has the following syntax: The condition must be a boolean expression. It must evaluate to either true or false. condition evaluated ifis a Java reserved word true false statement If the condition is true, the statement is executed. If it’s false, the statement is skipped. if ( condition ) statement; 5-6

  6. Boolean Expressions A condition often uses one of Java's equality operators or relational operators, which all return boolean results: ==equal to !=not equal to <less than >greater than <=less than or equal to >=greater than or equal to There’s a difference between the equality operator (==) and the assignment operator (=) 5-7

  7. The if Statement Here’s an if statement: if (sum > MAX) delta = sum - MAX; System.out.println ("The sum is " + sum); First the condition is evaluated -- the value of sum is either greater than the value of MAX, or it is not If the condition is true, the assignment statement is executed -- if it isn’t, it is skipped. The statement(s) controlled by the if statement are indented. The use of a consistent indentation style makes a program easier to read and understand 5-8

  8. The if Statement What do the following statements do? if (top >= MAXIMUM) top = 0; Sets top to zero if the current value of top is greater than or equal to the value of MAXIMUM if (total != stock + warehouse) inventoryError = true; Sets a flag to true if the value of total is not equal to the sum of stock and warehouse Which is performed first; the + or the != ??? 5-9

  9. Logical Operators Boolean expressions can also use the following logical operators: ! Logical NOT &&Logical AND ||Logical OR They all take boolean operands and produce boolean results Logical NOT is a unary operator (it operates on one operand) Logical AND and logical OR are binary operators (each operates on two operands) 5-10

  10. Logical AND and Logical OR The logical AND expression a && b is true if both a and b are true, and false otherwise The logical OR expression a || b is true if a or b or both are true, and false otherwise 5-11

  11. Logical Operators Expressions that use logical operators can form complex conditions final int MAX = 3; int total = 7; boolean found = false; if (total < MAX+5 && !found) System.out.println (“Is this line printed?"); What is the precedence here? How can you be sure? Boolean a = true, b = false, c = true if ( a && b || c ) System.out.println (“Is this line printed?…"); What happens on this line? 5-12

  12. Boolean Expressions Here are some more examples 5-13

  13. Example Program //******************************************************************** // MinOfThree.java Listing Example of random numbers and if logic // Generates three random numbers and finds the minimum of the three. //******************************************************************** import java.util.Random; public class MinOfThree { public static void main (String[] args) { final int LARGEST_NUMBER = 100; Random generator = new Random(); int num1, num2, num3, min = 0; num1 = generator.nextInt(LARGEST_NUMBER); num2 = generator.nextInt(LARGEST_NUMBER); num3 = generator.nextInt(LARGEST_NUMBER); System.out.println( “The three numbers are “ + num1 + “, “ + num2 + “, and “ + num3); if (num1 < num2) if (num1 < num3) min = num1; else min = num3; else if (num2 < num3) min = num2; else min = num3; System.out.println ("Minimum value: " + min); } // End of main } // End of MinOfThree Show BlueJ with this!!

  14. Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion while  from section 5.5 Interactive Programs Graphics Applets Drawing Shapes 15

  15. The while Statement If the condition is true, the statement is executed The statement is executed UNTIL the condition becomes false • A while statement has the following syntax: while ( condition ) statement; • An example of a while statement: int count = 1; while (count <= 5) { System.out.println (count); count++; } If the condition of a while loop is false initially, the statement is never executed The body of a while loop could execute zero or more times 5-16

  16. The while Statement • Keep getting data until user says “stop” while (value != 0) { // sentinel value of 0 to terminate loop count++; sum += value; System.out.println("The sum so far is " + sum); System.out.print("Enter an integer (0 to quit): "); value = scan.nextInt(); } • A loop can be used for input validation, making a program more bulletproof // Ensure user has input good data to us input = scan.nextInt(); // Get a value from user while (input< 0 || input> NUM_GAMES) { System.out.print ("Invalid input. Please reenter: "); input = scan.nextInt(); } 5-17

  17. An example of an infinite loop: int count = 1; while (count <= 25) { System.out.println (count); count = count - 1; } This loop will continue executing until interrupted (Control-C) or until an underflow error occurs An example of nested loops count1 = 1; while (count1 <= 3) { count2 = 2; while (count2 < 4) { System.out.println ("Here"); count2++; } count1++; } How many times will the string "Here" be printed? 5-18

  18. The do Statement • A do statement has the following syntax: do { statement; } while ( condition ) The statement is executed once initially, and then the condition is evaluated 5-19

  19. The do Statement • An example of a do loop: int count = 0; do { count++; System.out.println (count); } while (count < 5); The body of a do loop executes at least once 5-20

  20. The while Loop The do Loop condition evaluated statement true true false condition evaluated statement false Comparing while and do 5-21

  21. Example Program //********************************************************** // PalindromeTester.java Linting 5.10 - Modified // Tests strings to see if they are palindromes. //********************************************************** import java.util.Scanner; public class PalindromeTester { public static void main (String[] args) { String str, another = "y"; int left, right; Scanner scan = new Scanner (System.in); while (another.equalsIgnoreCase("y")) { // Loop while user wants another try System.out.println ("Enter a potential palindrome: "); str = scan.nextLine(); left = 0; right = str.length() - 1; while (str.charAt(left) == str.charAt(right) && left < right) { left++; right--; } if (left < right) System.out.println (“\nThat string is NOT a palindrome."); else System.out.println (“\nThat string IS a palindrome."); System.out.print (“\nTest another palindrome (y/n)? "); another = scan.nextLine(); } // End of while } }

  22. Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion For  from section 5.8 Interactive Programs Graphics Applets Drawing Shapes 23

  23. The statement is executed until the condition becomes false The initialization is executed once before the loop begins The increment portion is executed at the end of each iteration The for Statement • A for statement has the following syntax: for (int count=1; count <= 5; count++) System.out.println (count); The initialization section can be used to declare a variable The condition of a for loop is tested before executing the loop body The body of a for loop will execute zero or more times 5-24

  24. The for Statement for (int num=100; num > 0; num -= 5) System.out.println (num); The increment section can perform any calculation. A for loop is well suited for executing statements a specific number of times that can be calculated or determined in advance. 5-25

  25. Example Program //******************************************************************** // Stars.java Listing 5.14 - Modified // // Prints a triangle shape using asterisk (star) characters. //******************************************************************** public class Stars { public static void main (String[] args) { final int MAX_ROWS = 10; for (int row = 1; row <= MAX_ROWS; row++) { for (int star = 1; star <= row; star++) System.out.print ("*"); System.out.println(); } // End of for } // End of main() } // End of class Stars

  26. Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion If/for/while -- sections 5.2, 5.5, 5.8 Interactive Programs Graphics Applets Drawing Shapes 27

  27. Interactive Programs • Programs generally need input on which to operate • The Scanner class provides convenient methods for reading input values of various types • A Scanner object can be set up to read input from various sources, including the user typing values on the keyboard • Keyboard input is represented by the System.in object 28

  28. Reading Input • The following line creates a Scanner object that reads from the keyboard: Scanner scan = new Scanner (System.in); • The new operator creates the Scanner object • Once created, the Scanner object can be used to invoke various input methods, such as: answer = scan.nextLine(); This is an IMPORTANT example of a concept we’ll be using a lot: Scanner is a class. The “new” operation creates an object (named scan here) that is an instance of that class. That instance contains data that we can extract using methods such as nextLine(); 29

  29. Reading Input • The Scanner class is part of the java.util class library, and must be imported into a program to be used import java.util.Scanner; • More on object creation and class libraries in Chapter 3. • Usually, white space is used to separate the elements (called tokens) of the input • White space space characters, tabs, new line characters • The next method of the Scanner class reads the next input token and returns it as a string • Methods such as nextInt and nextDouble read data of particular types 30

  30. Example Program //************************************************************** // GasMileage.java Author: Lewis/Loftus // // Use of the Scanner class to read numeric data. // Calculates fuel efficiency based on inputs from the user. //************************************************************** import java.util.Scanner; public class GasMileage{ public static void main (String[] args) { int miles; double gallons, mpg; Scanner scan = new Scanner (System.in); System.out.print ("Enter the number of miles: "); miles = scan.nextInt(); System.out.print ("Enter the gallons of fuel used: "); gallons = scan.nextDouble(); mpg = miles / gallons; System.out.println ("Miles Per Gallon: " + mpg); } } 31

  31. Sample use of Inputs // Synonym.java Breecher 10/13/09 // Given a word, find its synonym // This example makes use of Scanner and also opens a URL to read a web page. // import java.util.Scanner; import java.net.*; import java.io.*; public class Synonym { public static void main( String[] argv) throws Exception { Scanner terminal = new Scanner( System.in ); System.out.println( "Give me a word" ); String input = terminal.nextLine(); String Address = "http://thesaurus.reference.com/browse/" + input; URL net = new URL( Address ); BufferedReader in = new BufferedReader( new InputStreamReader( net.openStream())); String inputLine, wholeLine = ""; while ((inputLine = in.readLine()) != null) { wholeLine = wholeLine + inputLine; } System.out.println(wholeLine); in.close(); } // End of main } // End of Synonym 32

More Related