Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 6: Midterm Review Tami Meredith. Programming Process How do we fill in the yellow box? Text Editor Compiler (javac) Interpreter (JVM: java) User.

Similar presentations


Presentation on theme: "Lecture 6: Midterm Review Tami Meredith. Programming Process How do we fill in the yellow box? Text Editor Compiler (javac) Interpreter (JVM: java) User."— Presentation transcript:

1 Lecture 6: Midterm Review Tami Meredith

2 Programming Process How do we fill in the yellow box? Text Editor Compiler (javac) Interpreter (JVM: java) User Libraries Operating System (Windows) OutputInput JDK

3 Programming Requires 1. Identification of the problem Understanding it, identifying correct solutions 2. Solving the problem: A. Selecting the data structures, and Data Management is the key here B. Identifying an algorithm Control Flow is the basis of algorithms 3. Coding the solution 4. Testing, debugging, verifying the solution

4 What is a Program? Programs = Data + Algorithms a. Data: the nouns, the things we manipulate b. Algorithms: the verbs, the actions we perform A program manipulates the input (data) to produce the required output (data)

5 Some Common Data Types Strings: Sequences of characters "hi there", "Hello, Bob!", "x", "RESULT" Integers: Whole numbers -3097, -2, -1, 0, 1, 10, 10340 Floating Point Numbers: Things with a decimal 1.0, 3.14,.333, 100000.0000001 Booleans: Truth values for tests true, false (that’s it, just two Boolean values)

6 Integers There are four kinds of integers The main difference is the minimum and maximum values byte : -128 to 127 short : -32 768 to 32 767 int : -2 147 483 648 to 2 147 483 647 long : -9 223 372 036 854 775 808 to 9 223 372 036 854 775 807 Difference is caused by the amount of memory used to store each one byte = 1 byte, short = 2 bytes in t = 4 bytes long = 8 bytes

7 Variables 1. int i; Defines a section of memory large enough to hold an integer and names that area of memory " i ", the memory contains a random value from whatever it was used for previously 2. i = 5; Stores the value 5 in the area or memory named " i " 3. int i = 5; Combines 1. and 2. A variable holds one, and only one, thing A variable always has a value... if you put nothing there then assume it has a random value

8 Variables Variables describe memory locations Values are stored in those locations Identifiers name locations int x = 13; location x 13 Right Hand Side (of = ): Use the value stored in the location (used also when no = in expression) Left Hand Side (of = ): Use the location to store the value

9 Operators Standard math: +, -, *, / Modulus (Remainder): % Assignment to a variable name uses = Can change the type of something using a cast int x = 1; float y = (float) x; + is also string concatenation e.g., "Hi " + "there" creates "Hi there"

10 Delimiters 1. " " A string (sequence of zero or more characters) 2. 'a' A character (a single character, never empty) 3. { } A block (sequence of zero or more statements) 4. /* */ A multi-line comment 5. ( ) a. A math expression b. A test in a loop or conditional c. The parameters of a method call d. The parameters in a method declaration

11 Strings Strings are a special data type (Strings are actually objects) Ordered and numbered sequences of characters Indexed from 0 Delimited by double quotes E.g., "Hello World!", "", "tami" Large library of String manipulation methods exists

12 String Methods See Figure 2.5 in the text (page 86) length() returns the length of a string (as an integer) indexOf( string2 ) returns the index of string2 in string or -1 if string2 is contained in string equals( string2 ) returns TRUE if string equals string2 otherwise it returns FALSE String sentence = "Hello programming class"; int len = sentence.length(); boolean same = sentence.equals("Good bye!");

13 Exercise Write a program that has a single String variable containing your name (as 2 words) e.g., String name = "Tami Meredith"; The program will print out your initials e.g., Tami Meredith's initials are: TM

14 Solution public class initials { public static void main (String[] args) { String name = "Tami Meredith"; int first = 0; int second = name.indexOf(" ") + 1; System.out.print(name + "'s initials are: "); System.out.print(name.charAt(first)); System.out.println(name.charAt(second)); } // end main() } // end class initials

15 Control is Power! Control flow is actually very simple: 1. Everything is sequential, unless... 2. Something is optional Conditional Statements, i.e,. if 3. Something is repeated Looping Statements, i.e., do, for, while 4. Something complex is broken into simpler parts Methods (and classes, objects)

16 Programs in Java Programs are structured hierarchically: 1. Programs have 1 or more classes Files are named after the classes they contain 2. Classes contain 1 or more methods The class that is used to start execution must contain a method named main 3. Methods perform 1 or more actions 4. Actions are performed by statements

17 About Statements... Statements are like sentences in a programming language Statements usually end with a " ; " (semi-colon) Statements are performed sequentially, one after the other (generally left to right, top to bottom) For example: x = x + 1; y = 2 * x; System.out.println("Y is " + y);

18 Statements Expressions and assignments e.g., x = 3 * y; Conditional statements to make choices e.g., if (x == 0) System.exit(0); Loops to repeat things e.g., while (i > 0) System.out.println(i--); Blocks to group statements into a single statement e.g., { statement1; statement2; statement3;... }

19 Blocks Statements can be grouped into a block A block is treated like a single statement and can be used where a single statement is expected Blocks are formed by surrounding a group of statements with curly braces, " { " and " } " For example: { y = x * 2; System.out.print("Two times " + x + " is " + y); }

20 Conditional Statements Conditionals make a choice of whether a statement should be executed: Syntax: if ( test ) statement When test evaluates to true, statement is executed statement is singular, a block must be used to do more than one thing when test is true Alternate Syntax: if ( test ) statement 1 else statement 2 If test is equal to true then do statement 1 If test is equal to false then do statement 2 Note that there is no " ; " at the end of the conditional

21 Loops Executes a statement more than once Syntax: while ( test ) statement 1. Evaluate test 2. If test is equal to true, do step 3, otherwise done 3. Perform statement then go back to 1 Note that statement is singular and that the loop does not end with a " ; " (but statement does)

22 Example // Code fragment, counts from 0 to // the value "stop" input by the user int count = 0; int stop = user.nextInt(); while (count <= stop) { System.out.println(count); count = count + 2; } // end of loop, go back to test

23 Do Loops Similar to while loops but test is done at the end, not the beginning Syntax: do statement while ( test ); 1. Perform statement 2. Evaluate test 3. If test is equal to true, go back to step 1 Note that because there is no statement at the end, a " ; " is needed!

24 For Loops For loops add extra functionality to a basic loop Syntax: for ( init ; test ; step ) statement 1. Perform init 2. Evaluate test 3. If test is equal to true, go to step 4, otherwise done 4. Perform statement 5. Perform step, go back to step 2 Note that " ; " are used as separators between init, test, and step

25 Statements (again) A. A line of code that ends with a " ; " is a statement B. A Block is a statement C. A Conditional (with optional else part) is a statement D. A Loop (of any kind) is a statement Statements can be combined in many different ways, and often, the same thing can be done in several ways When you have choice in how to do something, focus on: 1. Clarity 2. Brevity 3. Everything else

26 Exercise Write a program that has a String variable containing your name and then prints out your name backwards E.g., htidereM imaT

27 Solution public class backwards { public static void main (String[] args) { String name = "Tami Meredith"; int index, len = name.length(); for (index = len - 1; 0 <= index; index--) { System.out.println(name.charAt(index)); } } // end main() } // end class backwards

28 Nested Loops Loops can contain other loops! int i, j, k; for (i = 0; i <= 10; i = i + 10) { for (j = 0; j < 10; j = j + 1) { k = i + j; System.out.println(k); } What does this output?

29 Exercise Write a program to count and then print the number of spaces in a sentence input by the user

30 Solution import java.util.Scanner; public class spaces { public static void main (String[] args) { Scanner keyboard = new Scanner (System.in); String input = keyboard.nextLine(); int index, spaces = 0; for (index = 0; index < input.length(); index++) { if (input.charAt(index) == ' ') { spaces++; } System.out.println(input + ": " + spaces + " spaces."); } // end main() } // end class spaces

31 Methods Methods permit us to reuse a block of code Methods permit us to simplify code by replacing a complicated part with a meaningful name Methods permit us to break difficult things into smaller (named) parts Methods permit us to hide the details of something

32 Data: In and Out Some methods require data to operate The data that are needed are called "parameters" The values that are "passed" to the parameters when the method is "called" are referred to as "arguments" Some methods generate new data that they wish to give back when they are done The data that is generated is called the "return value"

33 Method Definitions Always have a "visibility" indicator (e.g., public) Sometimes are declared as "static" Always have a return type (which is "void" if the method returns nothing) Always have a name Always have a list of parameters in parentheses (but the list might be empty) Always have a block of code public static void main (String[] args) { System.out.println("Hello World!"); }

34 Return Statements return causes a method to end return usually has a value in parentheses after it, e.g., return(0); the type of the value must match the "return type" of the method if the method returns void, return doesn't need the parentheses, e.g., return;

35 Example public class test { // Parameters are in RED // Arguments (to put in parameters) are in BLUE // define the method add3 – returns an int public static int add3 (int x, int y, int z) { return (x + y + z); // must be an int } // define the method main – returns nothing, i.e., void public static void main (String[] args) { // call the method add3 int sum = add3(2, 4, 6); System.out.println("The sum is: " + sum); } } // end class test

36 Exercise Write a method named first that takes a String as input and returns the first character of the string Do not worry about empty strings being passed to first

37 Solution public static char first (String s) { return (s.charAt(0)); }

38 How to write a program 1. Pick a name 2. Identify the code: // Q2 solution, by Tami Meredith 3. Define a class: public class name {... } 4. Write a main method: public static void main (String[] args) {... } 5. Identify the variables – what do you have to work with? What do you need to produce? 6. Determine an algorithm – how do I turn my input into my output? IMPORTANT: Do not think "using Java" at this point... just figure out ANY way to solve the problem. 7. Translate your algorithm into Java. Does Java provide the tools you need?

39 Cheat Sheet Suggestions Program template Basic output to the screen Basic input from the keyboard Listing 1.1 covers the first 3 points Primitive data types (Figure 2.1) String methods (Figure 2.5) Scanner methods (Figure 2.7) Comparisons (Figure 3.4), logical operators (Figure 3.7), examples of if statements Examples of do, while, for loops Examples of how to define and call methods Examples of how to use the % operator

40 The Usuals Nothing = Zero – don't leave questions blank, ANYTHING is better than nothing! There are no penalties for incorrect answers SHOTGUN approach – write anything and everything you think is possibly relevant if you don't know the actual answer Pseudo code, point-form, flow charts... If you don't know the Java, answer it some other way For T/F, Multiple-Choice, Matching, etc. GUESS if you have to – no negative scoring! Copy examples (from your cheat sheet) that you think might work, don't worry about perfection, just about getting a small part right Leave lots of space, add stuff later when you think of it Write code in pencil, bring an eraser Answer questions in any order – do easiest stuff first

41 Prime Numbers A number is prime if its only divisors are 1 and itself: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...  How would we test to see if a number is prime? Think about this, please...

42 To Do Go to the lab and ensure you have marks for Assignments 1 to 4 Prepare your "Cheat Sheet" for the exam One piece of paper, 8.5 x 11 inches, hand-written, double sided Re-read Chapters 1-5 Practice Programming


Download ppt "Lecture 6: Midterm Review Tami Meredith. Programming Process How do we fill in the yellow box? Text Editor Compiler (javac) Interpreter (JVM: java) User."

Similar presentations


Ads by Google