Presentation is loading. Please wait.

Presentation is loading. Please wait.

Review of CSCI 1226 What You Should Already Know.

Similar presentations


Presentation on theme: "Review of CSCI 1226 What You Should Already Know."— Presentation transcript:

1 Review of CSCI 1226 What You Should Already Know

2 n 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 n Comments  why and when we use them »to end-of-line: // … »multi-line: /* … */ »javadoc: /** … */ n Style  names and why they’re important  camelCase, CONSTANT_STYLE  indentation, spacing, line length

4 What You Should Already Know n 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 n String methods that return boolean values  equals, equalsIgnoreCase, startsWith, …

5 What You Should Already Know n 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 n Arrays  declare, create, get length of  standard loop for visiting every element

6 What You Should Already Know n 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 n 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 static, return type, name, parameters »body (including return command)  what a stub is and why we make them

8 What You Should Already Know n 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 n 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 n Today:  conditionals, loops, and arrays n Tuesday:  methods n Thursday:  data types n New(ish) material starts in week 2

11 Purpose of a Conditional n Maybe do some command  need to know the conditions for doing it if the user says they want fries add fries to the order n 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(*) n if user says “yes” to the question  say “FRIES!”  add the price of the fries to the total 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. (*) There is no try in CSCI 1226… Maybe add fries… Total depends…

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? ”); answer = kbd.nextLine(); if (answer.startsWith(“y”)) { System.out.println(“FRIES!”); total += 1.99; }… …add fries to the order if they say they want fries…

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

15 Using Conditionals n 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 n Look for “Do one of the following” or “if such-and-such, do …”

16 Building a Selection Structure n 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 nice.” print “It’s cool.” print “It’s cold!”

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

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

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

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

21 Building a Selection Structure n 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 n 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!”); } print “It’s hot!” (do nothing) print “It’s cold!” 30 <= temp 5 <= temp < 30 temp < 5 { } else if (5 <= temp) { But be careful with the conditions!

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

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

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

26 Exercise n Write a conditional to set letterGrade based on numericGrade:  numericGrade in 80..100  letterGrade is ‘A’  numericGrade in 70..79  letterGrade is ‘B’  numericGrade in 60..69  letterGrade is ‘C’  numericGrade in 50..59  letterGrade is ‘D’  numericGrade less than 50  letterGrade is ‘F’  (assume numericGrade is 0..100)

27 Purpose of a Loop n Do something multiple times  write “Hello” ten times for count goes from 1 to 10 write “Hello” n 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? n 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 n Enter six assignment grades: for loop for (int a = 1; a <= 6; ++a) { … } n Add up numbers until negative: while loop while (num >= 0) { … }

29 Before, During, and After n 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) After repeats One repetition

30 Before, During & After 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); Before repeats Repeats (6 times) After repeats One repetition

31 Before, During, and After n 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) After repeats One repetition

32 Before, During & After 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); Before repeats Repeats (until -1 entered) After repeats One repetition

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

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 Read Process

35 Exercise n 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 n Array type is just another data type int anIntVar;// anIntVar’s type is int int[] aBunchOfIntVars;// aBunchOfIntVars’ type is int[] n Create by adding [] to a data type  any data type! double[] aBunchOfDoubleVars; String[] aBunchOfStringVars; Scanner[] aBunchOfScannerVars; int[][] aBunchOfIntArrayVars;

37 Arrays n 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 n An array is a collection/list of variables  each element is of the base type »int, double, String, … n 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 n Array elements can be used individually… a[0] = a[1] + a[2] * a[3]; n …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 n Every array knows how long it is  use its “dot-length property”  someNumbers.length, someWords.length, … n Or if you have a variable for its length… double[] grades = new double[numStu]; for (int i = 0; i < numStu; ++i) { … } n 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… n 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 # temps[i] = kbd.nextDouble(); // read the # sum += num[i]; // add it to sum 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)); S.o.p((num[i] – ave));} WeeklyTemps.java

43 Exercise n 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? A1 A2 A3 A4 A5 A6 100 90 95 0 90 75 Your average: 75.0

44 To Be Continued… n Chapters 5 and 6  Methods  Objects


Download ppt "Review of CSCI 1226 What You Should Already Know."

Similar presentations


Ads by Google