Presentation is loading. Please wait.

Presentation is loading. Please wait.

What You Should Already Know

Similar presentations


Presentation on theme: "What You Should Already Know"— Presentation transcript:

1 What You Should Already Know
Review of CSCI 1226 What You Should Already Know

2 What You Should Already Know
Basic programming program class: class declaration, main method output: System.out, print & println variables: declaration, assignment, arithmetic data types: int, double, boolean, String input using Scanners: import, declare, and create nextInt, nextDouble, next, nextLine “tidying up” your input

3 What You Should Already Know
Comments why and when we use them to end-of-line: // … multi-line: /* … */ javadoc: /** … */ Style names and why they’re important camelCase, CONSTANT_STYLE indentation, spacing, line length

4 What You Should Already Know
Conditionals and boolean expressions maybe do: the if control comparisons: ==, !=, <, <=, >, >= logical operators: !, &&, || exactly one of two: if-else exactly (or at most) one of many: if-else-if String methods that return boolean values equals, equalsIgnoreCase, startsWith, …

5 What You Should Already Know
Loops definite loops: the for loop (count controlled) indefinite loops: the while loop sentinel control: Read-Test-Process-Read general control: Initialize-Test-Process-Update Arrays declare, create, get length of standard loop for visiting every element

6 What You Should Already Know
Methods (using) parts of the method call location/owner, method name, arguments return value (including void) Math methods: pow, sqrt, random, … Arrays methods: toString, sort String methods: toUpper, toLower, length, …

7 What You Should Already Know
Methods (creating) why we create methods reuse, hiding, abstraction the method’s task/purpose/job creating a class of related static methods parts of the method declaration public/private static, return type, name, parameters body (including return command) what a stub is and why we make them

8 What You Should Already Know
Data Types (using) class data types: String, Scanner, … variables, objects, and reference: String myName = “Mark”; Scanner kbd = new Scanner(System.in); asking objects questions getting information about them: getters changing their information: setters getting them to do things

9 What You Should Already Know
Data Types (creating) why we create data types: representation creating a class for a data type parts of the data type instance variables (private) and constants (final) constructors: assigning values, this(…) creating getter and setter methods: this.___ static variables, constants, and methods why, when, and how

10 Review Outline Today: Next week: Following week:
conditionals, loops, and arrays Next week: arrays and methods, multi-dimensional arrays Following week: data types and the Javabean pattern

11 Purpose of a Conditional
Maybe do some command need to know the conditions for doing it if the user says they want fries add fries to the order Choose between multiple actions set the letter grade based on the percent grade: 80 or more: A; 70 to 79: B, 60 to 69: C, 50 to 59: D; otherwise F

12 Do or Do Not(*) if user says “yes” to the question say “FRIES!”
What sandwich? Big Greesie BIG GREESIE! Would you like fries with that? yes FRIES! What can I get you to drink? Cola COLA! That'll be $11.93. What sandwich? Big Greesie BIG GREESIE! Would you like fries with that? no What can I get you to drink? Cola COLA! That'll be $9.94. Maybe add fries… Total depends… Total depends… if user says “yes” to the question say “FRIES!” add the price of the fries to the total (*) There is no try in CSCI 1226…

13 Do or Do Not System.out.print(“What sandwich? ”);
answer = kbd.nextLine(); System.out.println(answer.toUppercase() + “!”); total += 8.95; System.out.print(“Want fries with that? ”); if (answer.startsWith(“y”)) { System.out.println(“FRIES!”); total += 1.99; } if they say they want fries… …add fries to the order

14 Cascading If Statements
Else part can have an if command in it if (…) { …; // program might do this… } else if (…) { …; // …or this… } else { …; // …or this. } program chooses one of those four things to do

15 Using Conditionals Conditionals are used when you need to do only one of multiple possible actions remembering that “do nothing” may be one of the possible actions Look for “Do one of the following” or “if such-and-such, do …”

16 Building a Selection Structure
Enumerate the alternatives what are the possible actions? is do nothing one of the alternatives? print “It’s hot!” print “It’s warm.” print “It’s cool.” print “It’s cold!” print “It’s nice.”

17 Building a Selection Structure
Identify the conditions when is each action the right thing to do? 30 <= temp print “It’s hot!” 25 <= temp < 30 print “It’s warm.” 5 <= temp < 15 print “It’s cool.” temp < 5 print “It’s cold!” 15 <= temp < 25 print “It’s nice.”

18 Building a Selection Structure
Sort the options from “largest” to “smallest”… …or from “smallest” to “largest” 30 <= temp print “It’s hot!” 25 <= temp < 30 print “It’s warm.” 15 <= temp < 25 print “It’s nice.” 5 <= temp < 15 print “It’s cool.” temp < 5 print “It’s cold!”

19 Building a Selection Structure
Assign if/else-if/else first is if; last is else; others are else if if 30 <= temp print “It’s hot!” else if 25 <= temp < 30 print “It’s warm.” else if 15 <= temp < 25 print “It’s nice.” else if 5 <= temp < 15 print “It’s cool.” else temp < 5 print “It’s cold!”

20 Building a Selection Structure
Simplify the conditions drop the part that’s implied We won’t get here unless temp < 30 if 30 <= temp print “It’s hot!” else if 25 <= temp print “It’s warm.” else if 15 <= temp print “It’s nice.” else if 5 <= temp print “It’s cool.” Nor here unless temp < 5 else print “It’s cold!”

21 Building a Selection Structure
Add parentheses, indentation, braces, … if (30 <= temp) { System.out.print(“It’s hot!”); } else if (25 <= temp) { System.out.print(“It’s warm.” ); } else if (15 <= temp) { System.out.print(“It’s nice.” ); } else if (5 <= temp) { System.out.print(“It’s cool.” ); } else { System.out.print(“It’s cold!” ); }

22 Building a Selection Structure
If there is a do nothing option, leave it out if (30 <= temp) { System.out.print(“It’s hot!”); } else if (temp < 5) { System.out.print(“It’s cold!”); } 30 <= temp print “It’s hot!” But be careful with the conditions! 5 <= temp < 30 (do nothing) temp < 5 print “It’s cold!” { } else if (5 <= temp) {

23 Boolean Expressions Comparison operators:
==, !=, <, <=, >, >= equals, not equals, less, less or equal, … (hours <= 40) Logical operators combine conditions and, or, not  &&, ||, ! parentheses recommended (needed for !) ((40 < hours) && (hours <= 60))

24 Combined Comparisons Cannot combine comparisons like this:
if (40 < hours <= 60) Need to break into two parts: if ((40 < hours) && (hours <= 60))

25 Combined Comparisons Cannot combine comparisons like this:
if (hours > 40 && <= 60) Need to say what’s less-than-or-equal-to 60 explicitly if ((hours > 40) && (hours <= 60))

26 Exercise Write a conditional to set letterGrade based on numericGrade:
numericGrade in  letterGrade is ‘A’ numericGrade in  letterGrade is ‘B’ numericGrade in  letterGrade is ‘C’ numericGrade in  letterGrade is ‘D’ numericGrade less than 50  letterGrade is ‘F’ (assume numericGrade is )

27 Purpose of a Loop Do something multiple times
write “Hello” ten times for count goes from 1 to 10 write “Hello” Do same thing to many objects/values add each number to a running total for each number in the list add that number to the running sum

28 How Many Times? Do we know how many times the loop body will execute before we start the loop? if so, we want to use a for loop if not, then we want to use a while loop Enter six assignment grades: for loop for (int a = 1; a <= 6; ++a) { … } Add up numbers until negative: while loop while (num >= 0) { … }

29 Before, During, and After
Notice part that repeats, and parts that don’t Enter all your grades. Grade on A1: 100 Grade on A2: 90 Grade on A3: 95 Grade on A4: 0 Grade on A5: 100 Grade on A6: 95 Your average is 80.0 Before repeats Repeats (6 times) One iteration After repeats

30 Before, During & After System.out.println(“Enter all your grades.”);
Before repeats System.out.println(“Enter all your grades.”); int numAsgn = 6; double sum = 0.0; for (int a = 1; a <= numAsgn; a++) { System.out.print(“Grade on A-” + a + “: ”); double grade = kbd.nextDouble(); kbd.nextLine(); sum += grade; } double ave = sum / numAsgn; System.out.println(“Your average is ” + ave); Repeats (6 times) One iteration After repeats

31 Before, During, and After
Notice part that repeats, and parts that don’t Enter -1 to end. Enter first number: 100 Enter next number: 90 Enter next number: 95 Enter next number: 42 Enter next number: -1 The total is 327 Before repeats Repeats (until -1 entered) One iteration After repeats

32 Before, During & After int sum = 0.0;
Before repeats int sum = 0.0; System.out.println(“Enter -1 to end.”); System.out.print(“Enter first number: ”); int num = kbd.nextInt(); kbd.nextLine(); while (num >= 0){ sum += num; System.out.print(“Enter next number: ”); num = kbd.nextInt(); kbd.nextLine(); } System.out.println(“The total is ” + sum); Repeats (until -1 entered) One iteration After repeats

33 “Sentinel” Loops Goes until a special value is entered
any number less than 0 for the last loop even tho’ it asked specifically for -1 Usually need to get 1st value before the loop then use the value (top of loop body) get the next value last (bottom of loop body) READ TEST PROCESS

34 “Sentinel” Loop int sum = 0.0; System.out.println(“Enter -1 to end.”);
System.out.print(“Enter first number: ”); int num = kbd.nextInt(); kbd.nextLine(); while (num >= 0){ sum += num; System.out.print(“Enter next number: ”); num = kbd.nextInt(); kbd.nextLine(); } System.out.println(“The total is ” + sum); Read Test Process Read

35 Exercise Write a loop to read in names, stopping when no name is entered. Say how many names there were. Who is in your class? Name (leave blank to end): Alex Name (leave blank to end): Bernard Name (leave blank to end): Cathy Name (leave blank to end): There are 3 students in your class. Remember: READ, test, process, read

36 Arrays Array type is just another data type
int anIntVar; // anIntVar’s type is int int[] aBunchOfIntVars; // aBunchOfIntVars’ type is int[] Create by adding [] to a data type any data type! double[] aBunchOfDoubleVars; String[] aBunchOfStringVars; Scanner[] aBunchOfScannerVars; int[][] aBunchOfIntArrayVars;

37 Arrays Arrays need to be created with “new” like Scanners
double[] someNumbers = new double[20]; String[] someWords = new String[1000]; word after “new” matches the base data type base data type = what kind of values are in the array put the size of the array in the [brackets] the size can be a variable, but it must have a value int howManyLines = kbd.nextInt(); kbd.nextLine(); String[] theLines = new String[howManyLines];

38 Arrays An array is a collection/list of variables
each element is of the base type int, double, String, … Individual variables picked out using [] someNumbers[3] brackets go right after the name of the array number inside the brackets called the index indexes (or indices) start at 0 (NOT 1!)

39 Array Loops Array elements can be used individually…
a[0] = a[1] + a[2] * a[3]; …but usually used as a group/list do same thing to each element of the array for (int i = 0; i < someNumbers.length; ++i) { someNumbers[i] = Math.sqrt(i); } usually in a for loop usually from 0 to less than the length of the array

40 Array Loop Upper Bounds
Every array knows how long it is use its “dot-length property” someNumbers.length, someWords.length, … Or if you have a variable for its length… double[] grades = new double[numStu]; for (int i = 0; i < numStu; ++i) { … } Do not use a “magic number” double[] grades = new double[100]; for (int i = 0; i < 100; ++i) { … } It’s error-prone (tends to add bugs to your program)

41 Use Arrays… To remember lots of values
read & print 3 numbers in reverse is easy int a1, a2, a3; a1 = kbd.nextInt(); a2 = kbd.nextInt(); a3 = kbd.nextInt(); System.out.println(a3 + “ ” + a2 + “ ” + a1); but read and print 300 numbers in reverse?!?! int[] a = new int[300]; for (int i = 0; i < a.length; i++) { a[i] = kbd.nextInt(); } for (int i = a.length – 1; i >= 0; i--) { Sop(a[i] + “ ”); } well that was pretty easy, too!

42 Remember Values for Later Use
// read and sum the numbers double[] temps = new double[7]; double sum = 0.0; S.o.p(“Enter ” + temps.length + “ daily highs.”); for (int i = 0; i < NUM_ITEMS; i++) { temps[i] = kbd.nextDouble(); // read the # sum += num[i]; // add it to sum } kbd.nextLine(); // tidy up input stream // calculate the average double ave = sum / temps.length; // print the difference from the average of each for (int i = 0; i < temps.length; i++) { S.o.p((num[i] – ave)); WeeklyTemps.java

43 Exercise Create a program fragment to read in six grades, then print them in a table and show the average: labels and grades separated by tabs lines end after the labels/numbers are printed so where does the System.out.println() go? A A A A A A6 Your average: 75.0

44 To Be Continued… Next two weeks: Methods Objects


Download ppt "What You Should Already Know"

Similar presentations


Ads by Google