Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 2: 1226 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 2: 1226 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 2: 1226 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 Characters: Things from the keyboard 'a', 'b', 'Z', '!', '\n' Strings: Sequences of characters "hi there", "Hello, Bob!", "x", "RESULT" Integers: Whole numbers, byte, short, int, long -3097, -2, -1, 0, 1, 10, 10340 Floating Point Numbers: float, double (have decimals) 1.0, 3.14,.333, 100000.0000001 Booleans: Truth values for tests true, false Nothing: The empty type with no value void

6 ASCII Every character has a value We store the value, not the character We can treat characters as numbers as a consequence The values assigned are based on the ASCII encoding 0-127: Basic ASCII 128-255: Extended ASCII 256-65535: Unicode (subsumes ASCII)

7

8 Escaped Characters Sometimes we want to remove or add meaning to characters in a string (Figure 2.6) Can also use this notation to represent characters from the ASCII table To do this we use the escape character '\' to escape the normal meaning of the next character \" – double quote, don't end the string \' – single quote \\ - just a backslash, not an escape \n – newline (go to beginning of next line) \t – tab, expanded using system default \r – carriage return (same as newline... maybe)

9 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

10 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

11 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

12 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"

13 See: Text Fig 3.9

14 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. [ ] An array index 6. ( ) a. A math expression b. A test in a loop or conditional c. The arguments of a method call d. The parameters in a method declaration

15 printf An alternative to print or println Very powerful and flexible e.g., System.out.printf("An integer: %d", i); Format: System.out.printf( format-string, values... ); The format-string is printed and every specifier (things that begin with a % ) is replaced with one of the values There must be the same number of values as specifiers It was originally in the C programming language and was added to Java because a lot of C programmers wanted it! Described on page 101 – 102

16 Format Specifiers %c – a character %s – a string %d – an integer %f – a floating point number We can modify the values to have a minimum and a maximum size, left or right justify numbers, pad with leading/trailing zeros, create columns, etc. E.g., %5d – an integer with 5 digits (spaces added if needed) See: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

17 printf printf ( format-string,... values... ) There must be one value for every specifier in the format string format specifiers begin with a % and are placed in the format string E.g. printf("Hello %s!", name); In this example %s means, put a string here, and name is used to provide the string Same as print("Hello " + name + "!"); There might not be any values! E.g., printf("Hello!"); is the same as print("Hello!");

18 Examples System.out.printf ("%d * %d = %d\n", 3, 4, 3*4); System.out.println(3 + " * " + 4 + " = " + (3*4)); System.out.print (3 + " * " + 4 + " = " + (3*4) + "\n"); 3 * 4 = 12 System.out.printf ("%s\n%s\n", "Tami", "Meredith"); System.out.println("Tami\nMeredith"); System.out.print ("Tami\nMeredith\n"); Tami Meredith

19 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

20 String Methods See Figure 2.5 in the text (page 86) replace(c1,c2) and replace(ss1,ss2) replace all occurances of c1 / ss1 with c2 / ss2 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!");

21 Exercise Write a program that has a single String variable containing your name as 2 or more words e.g., String name = "Tami Michelle Meredith"; The program will tell you how many words your name had. The program must still work correctly if someone changes the name to have a different number of words. e.g., Tami Michelle Meredith has 3 names.

22 Solution public class howMany { public static void main (String[] args) { String name = "Tami Michelle Meredith"; String spaceless = name.replace(" ", ""); int num = name.length() – spaceless.length() + 1; System.out.println(name + " has " + num + " names."); } // end main() } // end class howMany

23 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)

24 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

25 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);

26 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;... }

27 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); }

28 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

29 Conditional Expressions if (sex == 'f') System.out.printf("female"); else System.out.printf("male"); > System.out.printf("%smale", (sex=='f') ? "fe" : ""); Format: ( test ) ? use-if-true : use-if-false

30 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)

31 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

32 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!

33 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

34 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?

35 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

36 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?

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

38 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

39 Keyboard Input It is useful to get input from the user System.in is an object of type InputStream It is not very useful since you can only read bytes from an InputStream We apply a Scanner to the InputStream to 1. Break the stream into meaningful parts (e.g., integers, lines, words) 2. Change the parts into useful types (e.g., ints, floats, Strings )

40 Useful Methods See Figure 2.7 (Page 98) of the text next(), gets the next word nextLine(), gets the next line, discards the newline nextInt(), gets the next integer hasNextLine(), checks if there is another line, returns a boolean hasNextInt(), checks if there is another int, returns a boolean There are many other methods you can use, see: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

41 Echo Example Scanner reader = new Scanner(System.in); String input; do { input = reader.nextLine() System.out.printf("%s",input); } while (!input.equals("quit");

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

43 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

44 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

45 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"

46 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!"); }

47 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;

48 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

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

50 Solution public static char last (String s) { return (s.charAt(s.length()-1)); }

51 Exercise Write a method called digital that takes a single String as its parameter and returns a new string that contains all the digits (i.e., 0 to 9 ) in the original string e.g., digital("Tip 7: Bet on #3 in the 8th.") returns "738"

52 Solution public static String digital (String in) { String out = ""; for (int i = 0; i < in.length(); i++) { char c = in.charAt(i); if (('0' <= c) && (c <= '9')) if (Character.isDigit(c)) { out = out + c; out += c; } return (out); } // end digital()

53 Moving Right Along...

54 To Do Do Assignment 1 in the lab today Read and fully understand Chapters 1-4 and 7 (arrays) Ensure you can do all the exercises in the class today


Download ppt "Lecture 2: 1226 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