Download presentation
Presentation is loading. Please wait.
Published byMaude Stanley Modified over 9 years ago
1
CSCI 1226 Fall 2014 Reviews Section B
2
Computers Types of computers: Personal computers Embedded systems Servers Hardware: I/O devices: mice, keyboards, monitors, etc CPU (Central Processing Unit) Memory, Main/Primary vs secondary Exam tip! Examples of each type? Exam tip! Examples of each type? Exam tip! What are the differences? Exam tip! What are the differences?
3
…Computers Software: Data & instructions »Algorithm »Pseudo-code Data hierarchy: »8 bits byte »1 or more bytes data value (field) »1 or more data values/objects object (record) »data may be stored on secondary memory (file) Exam tip! What are the differences? Exam tip! What are the differences? Exam tip! An object can contain other objects! Exam tip! An object can contain other objects!
4
Java Programming Basics IDE: Integrated Development Environment Variables: Data types Naming rules and conventions Math and special assignment operators +, -, *, /, % +=, -=, *=, /=. %= ++, --
5
…Java Programming Basics Output: System.out.println() and System.out.print() »Print spaces »With or without quotes »Concatenation (using +, with math expressions, etc) User input: Scanner class: instantiation, import, etc next(), nextLine(), nextInt(), nextDouble(), etc Use nextLine() to »flush the input buffer Exam tip! How to pause a program using nextLine()? See Utilities.java Exam tip! How to pause a program using nextLine()? See Utilities.java Exam tip! Print all values in one line or each value in one line Exam tip! Print all values in one line or each value in one line
6
Conditionals Syntax: if, if-else, if-else if, if-else if … else Comparison operators ==, !=,, = Logical operators && (AND), || (OR), ! (NOT)
7
… Conditionals Sequential and nested if-else: Convert one to the other What’s the output?: What’s the code? Possible outcomes: outcome #1: A, B, C, E, F outcome #2: A, D, E, F System.out.print(“A”); if (...) { System.out.print(“B”); } if (...) { System.out.print(“C”); if (...) { System.out.print(“D”); } else { System.out.print(“E”); }
8
boolean variables Can save the answer to a comparison use a boolean variable boolean workedOvertime = (hours > 40); »you don’t need parentheses, but it’s easier to read E.g.) Write Boolean expressions for whether… x is greater than 0 and y is less than 5 x is greater than zero or y is equal to z it’s not the case that x is greater than the product of y and z Exam tip! “whether” boolean Exam tip! “whether” boolean
9
… boolean variables Break complex expressions down boolean failedMidterm = (midtermGrade < 50); boolean failedFinal = (finalGrade < 50); boolean failedBothTests = failedMidterm && failedFinal; String comparisons (all return boolean values) oneString.equals(anotherString) oneString.equalsIgnoreCase(anotherString) oneString.startsWith(anotherString) oneString.endsWith(anotherString) Exam tip! boolean a = true, b = false, c = false; !a a && b (a || c) && (!b && !c) (a && !b) || c Exam tip! boolean a = true, b = false, c = false; !a a && b (a || c) && (!b && !c) (a && !b) || c
10
Loops for and while loops Convert between them Loop structure Initialize, test/condition, update, process for (initialize; test; update) { process; } initialize; while (test) { process; update; } Exam tip! When asked for an algorithm, make sure to include all these 4 steps! Exam tip! When asked for an algorithm, make sure to include all these 4 steps!
11
… Loops Write loops to: Calculate sum, average, max, min, of numbers When to stop? »Negative number »Yes/no Track the variable’s values: a = 1; a++; b = a + 6; b--; c = b * 5; c += a; a *= 10; b /= 2; c %= 4; a *= b + c; Exam tip! Write the loops for these with or without arrays! Exam tip! Write the loops for these with or without arrays!
12
Named Constants public static final data-type CONST_NAME = value Naming conventions variableName CONSTANT_NAME
13
Nested structures Loops with Conditionals while (num >= 0) { // say whether num is divisible by 5 // say whether num is divisible by 5 if (num % 5 == 0) { if (num % 5 == 0) { System.out.println(num + “ is divisible by 5.”); System.out.println(num + “ is divisible by 5.”); } else { } else { System.out.println(num + “ is not divisible by 5.”); System.out.println(num + “ is not divisible by 5.”); } // get next number // get next number num = kbd.nextInt(); num = kbd.nextInt();}
14
… Nested structures if inside if: System.out.println(“A”); if (condition1) { System.out.println(“B”); System.out.println(“B”); if (condition2) { if (condition2) { System.out.println(“C”); System.out.println(“C”); }} possible output: A AB ABC pattern: always A sometimes B when B, sometimes C
15
… Nested structures Rewrite sequential-if to cascading-if if (age < 18) { System.out.print(“Child”); } if (age >= 18 && age < 65) { System.out.print(“Adult”); } if (age >= 65) { System.out.print(“Senior”); } if (age < 18) { System.out.print(“Child”); } else if (age < 65) { System.out.print(“Adult”); } else { System.out.print(“Senior”) ; }
16
… Nested structures Loops inside loops: Review A05 Draw a rectangle: »Get w and h from user Draw a tree: »Given the base size Exam tip! A05 Solution is posted! Check it out! Exam tip! A05 Solution is posted! Check it out!
17
Scopes of a variable/parameter Inside loops Inside if-else Inside method (variables and parameters) Inside class (instance and class variables)
18
Methods Exam tip! str.equals(), str.startsWith(), str.toUpperCase() kbd.next(), kbd.nextLine(), etc Exam tip! str.equals(), str.startsWith(), str.toUpperCase() kbd.next(), kbd.nextLine(), etc
19
… Methods For reading data (kbd is a Scanner) kbd.nextInt() kbd.nextDouble() kbd.next() kbd.nextLine() For checking strings (resp is a String) resp.equals(“yes”) resp.equalsIgnoreCase(“yes”) resp.startsWith(“y”) resp.toLowerCase()
20
Arguments “Arguments” are given to the method »we also say that the method takes arguments Math.sqrt(10) – 10 is the (only) argument »asks Math for the square root of 10 Math.pow(5, 2) – 5 and 2 are both arguments »asks Math for 5 to the power 2 (i.e. 5 2 ) arguments must be in the right order! »Math.pow(2, 5) is 2 5, not 5 2
21
Argument Types Arguments must be the right type! Math.pow(“fred”, true) makes no sense! »the two arguments must be numbers »doubles are OK: Math.pow(3.7, 1.98) resp.startsWith(7) makes no sense! »the argument must be a String: resp.startsWith(“7”) And in the right order and there must be the right number of them! »Math.pow(5) and Math.pow(1, 2, 3) make no sense!
22
Exercise Assume the calls below are correct. What argument type(s) does each method take? Math.getExponent(3400.2) Math.ulp(2.6) Math.scalb(4.5, 2) str.split(“:”, “one:two:three:four”) str.length() str.regionMatches(true, 0, “this”, 7, 50)
23
Return Types Methods can return any kind of value »(or even none) Math.sqrt(10) returns a double value Math.max(3, 5) returns an int value kbd.nextInt() returns an int value kbd.next() returns a String value str.toUpperCase() returns a String value str.indexOf(“n”) returns an int value
24
Exercise Assuming the code below is correct, what kind of value does each method return? double x, y = 3.2; int n = 42; String name = “Mark”; boolean good; name = name.replaceFirst(“a”, “o”); x = Math.exp(y); n = Math.getExponent(x); good = (name.equalsIgnoreCase(“mork”));
25
Exercise Void or value-returning? & what kind of value does each VRM return? if (answer.startsWith(“Y”)) { double x = Math.pow(3, 6); double x = Math.pow(3, 6); int n = kbd.nextInt(); int n = kbd.nextInt(); System.out.println(“Hello!”); System.out.println(“Hello!”); myWin.setVisible(true); myWin.setVisible(true); double cm = Converter.cmFromFeetInches(n, x); double cm = Converter.cmFromFeetInches(n, x); thingamajig.doStuff(cm, x, that.get(n)); thingamajig.doStuff(cm, x, that.get(n));} Note: there are two method calls on the last line. How can we find out what kind of value get returns?
26
Method declaration Header: 1.public/private 2.static (or non-static) 3.return-type (void, int, double, String, boolean, Class, etc) 4.methodName 5.(paramType1 param1, paramType2 param2, …) E.g.) »public static double fahrenheitFromCelsius(double degC) »public boolean equalsTo(int a[], int b[]) »private int[] subtract(int a[], int b[]) Exam tip! Write a method that takes and returns Takes parameters Returns return type Exam tip! Write a method that takes and returns Takes parameters Returns return type
27
Arguments and Parameters Arguments are values (10, 15.4, “Hello”) Parameters are variables need to be declared like variables »(double degC), (int ft, double in) only differences are: »declarations are separated by commas, not ;s »every parameter needs its own type, even if they’re all the same type: (double x, double y, double z), (int a, int b)(double x, double y, double z), (int a, int b) Exam tip! Given a list of parameters, a method call needs to have corresponding argument list! Exam tip! Given a list of parameters, a method call needs to have corresponding argument list!
28
Method Body The method body is where you tell the computer how to compute the value needed »how to convert feet and inches to cm »how to convert Celsius to Fahrenheit »... Need to know how to do it... »feet times 12 plus inches, all multiplied by 2.54 ...and translate it into Java: result = (ft * 12 + in) * 2.54;
29
… Method Body Anything you can do in main … …you can do in a method (local) variable declarations (including objects) assignment statements selection controls (if, if-else, if-else-if) repetition controls (while, for) method calls (other things we haven’t learned about yet) Exam tip! Did you see the related question in midterm? Exam tip! Did you see the related question in midterm?
30
Method “Stubs” Our methods need return commands need to return the right kind of thing we want to return exactly the right value but Java doesn’t care! So we can just put a “dummy” return in return something so that Java doesn’t complain worry about making it right later we call such a function a “stub” (it’s short) Exam tip! As long as your methods compile with proper parameter lists and return types, your stubs are good enough (for this course)! Exam tip! As long as your methods compile with proper parameter lists and return types, your stubs are good enough (for this course)!
31
Converter Class with Stubs public class Converter { public static double fahrenheitFromCelsius(double degC) { public static double fahrenheitFromCelsius(double degC) { return 0.0; return 0.0; } public static double cmFromFeetInches(int ft, double in) { public static double cmFromFeetInches(int ft, double in) { double result = 0.0; double result = 0.0; return result; return result; }} return statement is the last line of a method!
32
Naming Methods Method names in mixed case capital letter for 2 nd and subsequent words The same as variable’s naming convention
33
Putting them together public static returnType methodName(pType1 p1, pType2 p2) { body... body... return result; return result;} returnType, pType1 and pType2 are int, or double, or String, or Class, or an array, or any data type we’ve seen! methodName is the name of the method p1 and p2 are the parameters body is for the commands calculating the result static is only needed for class (static) methods
34
Classes vs. Objects Classes can be used right away Utilities.printTitle(“Utilities Demo”); »so long as we can “see” them Objects need to be created »except for Strings, which are so massively useful… Scanner kbd = new Scanner(System.in); objects contain data different objects have different data methods are mostly about that data Exam tip! static methods! Exam tip! static methods!
35
Declaring Objects Most Java objects created using new »usually with arguments »arguments depend on the class kbd = new Scanner(System.in); rover = new Animal(Animal.DOG);// I made this up! c1 = new Color(255, 127, 0);// This is orange okButton = new JButton(“OK”); »not Strings, tho’ s1 = “Strings are special!”; s2 = new String(“But this works, too!”); Remember to import java.awt.Color; import javax.swing.JButton;
36
Student Class (Start) public class Student { private String aNumber;// A00... private String name;// family name, givens private int pctGrade;// 0..100 …} Exam tip! instance variables are declared private (not public) no “static”; no “final”! Exam tip! instance variables are declared private (not public) no “static”; no “final”!
37
Java modifiers Access modifiers public private Non-access modifiers static final
38
Which modifiers? Instance variables private dataType Class variables private static dataType Instance constant public final dataType Class constant public static final dataType Exam tip! Class static Constant final Exam tip! Class static Constant final
39
Constructors Constructor “builds” the object gives a value to each of the instance variables private String aNumber;// A00… private String aNumber;// A00… private String name;// Last, First private String name;// Last, First private int grade;// 0.. 100 private int grade;// 0.. 100 public Student(String a, String n, int g) { public Student(String a, String n, int g) { aNumber = a; aNumber = a; name = n; name = n; grade = g; grade = g; } a, n, and g are the parameters: the values the caller wants to use; aNumber, name, and grade are the instance variables: the values we will use.
40
… Constructors Generally declared public anyone can build a Scanner, a Student, … Name is exactly the same as the class name class Student constructor named “Student” class Animal constructor named “Animal” No return type not even void! Argument for each instance variable (often)
41
… Constructors Their job is to give a value to each instance variable in the class and so often just a list of assignment commands »instanceVariable = parameter; aNumber = a; name = n; grade = g; But may want to check if values make sense so maybe a list of if-else controls
42
Checking Values If given value makes no sense, use a default »but still instanceVariable = (something); public Student(String a, String n, int g) { if (a.startsWith(“A”) && a.length() == 9) { if (a.startsWith(“A”) && a.length() == 9) { aNumber = a; aNumber = a; } else { } else { aNumber = “(illegal)”; aNumber = “(illegal)”; } name = n; name = n; …} Exam tip! Given object instantiation, write a constructor! int r, g, b; r = g = b = 0; Colour col = new Colour(r,g,b); Set values of r, g, b if between [0,255] Otherwise zero Exam tip! Given object instantiation, write a constructor! int r, g, b; r = g = b = 0; Colour col = new Colour(r,g,b); Set values of r, g, b if between [0,255] Otherwise zero
43
Create a Student object Student stu = new Student(“A00000000”, “Dent, Stu”, 100); The argument list should match the parameter list of the constructor (String a, String n, int g) The same as any other method calls public static boolean equalsTo(int a[], int b[]) int[] a = new int[len]; int[] b = new int[len]; if (ArrayOperations.equalsTo(a, b)) {}
44
Getters and Setters Getters: public String getANumber() { return aNumber; return aNumber;} Setters: public void setPctGrade(int newGrade) { if (0 <= grade && grade <= 100) { if (0 <= grade && grade <= 100) { pctGrade = newGrade; pctGrade = newGrade; }} Exam tip! Getters: public! Anyone can ask! Return type! Never void! Non-static! Each student has own name! Just return the instance variable! Exam tip! Getters: public! Anyone can ask! Return type! Never void! Non-static! Each student has own name! Just return the instance variable! Exam tip! Setters: public! Anyone can change! Return type! (usually) void! Non-static! Each student has own grade! Set the value (with some conditions) Exam tip! Setters: public! Anyone can change! Return type! (usually) void! Non-static! Each student has own grade! Set the value (with some conditions)
45
this keyword Text definition: “Within a method definition, you can use the keyword this as a name for the object receiving the method call.”
46
… this keyword public class SomeClass { private int var; public SomeClass(){ this.var = 0;//instance variable var = 0;//instance variable } public void incrementVar(int var){ this.var++;//instance variable var++;//local parameter!!! } public void printVar(){ System.out.println(this.var);//instance variable System.out.println(var);//instance variable }} Exam tip! this is only needed to disambiguate things. Exam tip! this is only needed to disambiguate things.
47
Instance (non-static) and class (static) Instance variables/methods Belongs to a particular object Each instance/object of the class has its own value IM uses object’s values (IV) Class (static) variables/methods Belongs to a particular class All the instances/objects of the class point to the same CV (hence, the same value) CM uses CV (static) values
48
final and Non-final final means once it’s assigned a value, you cannot change it (immutable)! Can be static and final (class constant) Or non-static and final (instance constant)
49
Class (static) Variables public class Student { public final String A_NUMBER; private String name; private int pctGrade; private static int nextANumber = 1; nextANumber belongs to Student class not to each Student, but to every Student
50
Assigning Student Numbers To create a student: assign the next available number update the next available number (continue setting other IVs) public Student(String n, int g) { A_NUMBER = String.format(“A%08d”, nextANumber); ++nextANumber;…} String.format is like System.out.printf, BUT it makes the String, it doesn’t print it
51
… Assigning Student Numbers Student s1, s2; Student s1, s2; s1 = new Student("Akiyama, Yasushi",75); s1 = new Student("Akiyama, Yasushi",75); s2 = new Student("Cooper, Ray",90); s2 = new Student("Cooper, Ray",90); System.out.println(s1.A_NUMBER); System.out.println(s1.A_NUMBER); System.out.println(s2.A_NUMBER); System.out.println(s2.A_NUMBER); Output: A00000001 A00000002
52
Car class public class Car { public final String VIN; private static int numCars = 0; //other constants and variables public Car(double tankSize, double fuelConsumption) { this.numCars++; VIN = String.format("CSCI1226%04d", this.numCars); //other operations }
53
… Car class // create a few cars Car car1 = new Car(45.0, 7.5); Car car2 = new Car(45.0, 6.8); Car car3 = new Car(40.0, 6.2); System.out.println(car3.VIN); Output: CSCI12260003
54
toString() method @Override public String toString() { return name + “ (” + A_NUMBER + “)” return name + “ (” + A_NUMBER + “)”} Call it explicitly: Student s = new Student(“Pat”, 80); System.out.println(s.toString()); Or implicitly: Student s = new Student(“Pat”, 80); System.out.println(s) ;
55
Arrays
56
Array Base Types Arrays can be of any base type, any size int[] score = new int[600]; double[] weight = new double[70]; boolean[] answers = new boolean[10]; String[] words = new String[5000]; …any type at all Scanner[] scanners = new Scanner[2]; Student[] myStudents = new Student[10]; The text recommends singular names. I tend to use plural. Exam tip! Make sure you know how to declare and create arrays of any data type! Exam tip! Make sure you know how to declare and create arrays of any data type!
57
Array Sizes Remember to declare constants for numbers you use in multiple places like in array declaration and loop! int[] nums = new int[NUM_ITEMS]; int[] nums = new int[NUM_ITEMS]; for (int i = 0; i < NUM_ITEMS; i++) for (int i = 0; i < NUM_ITEMS; i++) nums[i] = kbd.nextInt(); nums[i] = kbd.nextInt(); Makes it easy to change the number later // # elements – change to 600 when debugged! public static final int NUM_ITEMS = 6;
58
Arrays Know Their Own Length Array length public static final int MAX_WORDS = 200; … String[] word = new String[MAX_WORDS]; String[] word = new String[MAX_WORDS]; if (word.length != MAX_WORDS) { if (word.length != MAX_WORDS) { System.err.println(“Your computer is broken!”); System.err.println(“Your computer is broken!”);} Exam tip! Don’t confuse with String’s length() method! arr.length is not a method, hence no (), and it’s final so cannot be changed! (public final field length;) Exam tip! Don’t confuse with String’s length() method! arr.length is not a method, hence no (), and it’s final so cannot be changed! (public final field length;)
59
Creating Arrays with Values Create an array object by listing elements int[] arr = new int[]{2, 3, 5, 7, 11}; It knows its own length! for(int i = 0; i < arr.length; i++) { System.out.print(arr[i] + “ ”); } Can change the array later arr = new int[]{13, 17, 19, 23}; 2 3 5 7 11 Initialize.java
60
Average and Differences // read and sum the numbers int[] num = new int[NUM_ITEMS]; int sum = 0; S.o.p(“Enter the ” + NUM_ITEMS + “ items below”); for (int i = 0; i < NUM_ITEMS; i++) { num[i] = kbd.nextInt();// remember the # num[i] = kbd.nextInt();// remember the # sum += num[i];// add it to sum sum += num[i];// add it to sum} // calculate the average double ave = (double)sum / (double)NUM_ITEMS; // print the difference from the average of each for (int i = 0; i < NUM_ITEMS; i++) { S.o.p((num[i] – ave)); S.o.p((num[i] – ave));} WeeklyTemps.java
61
Arrays as Parameters Methods can have [] parameters, just declare the parameter to be an array! public static int sumArray(int[] arr) It’s just like any other parameter gets its value from the method call It’s just like any other array it knows how long it is
62
Method to Sum an Array Array comes from caller int[] n = new int[]{2, 3, 5, 7, 11}; int addedUp = sumArray(n); Method adds up its elements public static int sumArray(int[] arr) { int sum = 0; int sum = 0; for (int i = 0; i < arr.length; i++) { for (int i = 0; i < arr.length; i++) { sum += arr[i]; sum += arr[i]; } return sum; return sum;} ArrayMethod.java
63
Returning Arrays Methods can return arrays return type is an array type public int[] dice(int howMany) { … } public String[] wordsFrom(String line) { … } Like any other object-returning method, the object/array to be returned is new int[] result = new int[howMany]; … return result; ArrayReturn.java
64
Exercise Be able to write: equalsTo subtract max min from ArrayOperations.java
65
Final Exam (Section A) Saturday, December 6, 2014, 7:00 pm - 10:00 pm ME Auditorium Hand-written test -- bring pen & whiteout or pencil & eraser. No electronic devices allowed You may bring a reference sheet: A single 8.5x11 (A4) sheet of paper. It may be hand-written or printed. You may use both sides of the sheet. You can prepare it alone or with friends, but bring your own copy (no sharing copies during the test). If your sheet is too large (or otherwise breaks the rules), it will be confiscated.
66
Final Exam (Section B) Friday, December 12, 2014, 9:00 am - 12:00 pm Atrium 101 Hand-written test -- bring pen & whiteout or pencil & eraser. No electronic devices allowed You may bring a reference sheet: A single 8.5x11 (A4) sheet of paper. It may be hand-written or printed. You may use both sides of the sheet. You can prepare it alone or with friends, but bring your own copy (no sharing copies during the test). If your sheet is too large (or otherwise breaks the rules), it will be confiscated.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.