Upload
maude-stanley
View
215
Download
0
Embed Size (px)
Citation preview
CSCI 1226 Fall 2014 Reviews
Section B
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!What are the differences?
…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!An object can contain other objects!
Java Programming Basics
IDE: Integrated Development Environment Variables:
Data types Naming rules and conventions
Math and special assignment operators +, -, *, /, % +=, -=, *=, /=. %= ++, --
…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!Print all values in one line or each value in one line
Conditionals
Syntax: if, if-else, if-else if, if-else if … else
Comparison operators ==, !=, <, >, <=, >=
Logical operators && (AND), || (OR), ! (NOT)
… 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”); }}
boolean variables
Can save the answer to a comparison use a boolean variableboolean 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
… boolean variables
Break complex expressions downboolean 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;!aa && b (a || c) && (!b && !c) (a && !b) || c
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!
… 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!
Named Constants
public static final data-type CONST_NAME = value
Naming conventions variableName CONSTANT_NAME
Nested structures
Loops with Conditionalswhile (num >= 0) { // say whether num is divisible by 5 if (num % 5 == 0) { System.out.println(num + “ is divisible by 5.”); } else { System.out.println(num + “ is not divisible by 5.”); } // get next number num = kbd.nextInt();}
… Nested structures
if inside if:System.out.println(“A”);if (condition1) { System.out.println(“B”); if (condition2) { System.out.println(“C”); }} possible output:
AABABC
pattern:always Asometimes Bwhen B, sometimes C
… 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”);}
… 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!
Scopes of a variable/parameter
Inside loops Inside if-else Inside method (variables and parameters) Inside class (instance and class variables)
Methods
void vs value-returning System.out.println()? Math.sqrt(25.5)? etc
Use method calls in expressionsroot = (-b + Math.sqrt(b*b – 4*a*c)) / (2 * a);
Write math expressions in Java y = a = z =
Exam tip!str.equals(), str.startsWith(), str.toUpperCase()kbd.next(), kbd.nextLine(), etc
… 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()
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. 52)
arguments must be in the right order!» Math.pow(2, 5) is 25, not 52
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!
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)
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
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”));
Exercise
Void or value-returning? & what kind of value does each VRM return?if (answer.startsWith(“Y”)) { double x = Math.pow(3, 6); int n = kbd.nextInt(); System.out.println(“Hello!”); myWin.setVisible(true); double cm = Converter.cmFromFeetInches(n, x); 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?
Method declaration
Header:1. public/private2. static (or non-static)3. return-type (void, int, double, String, boolean, Class, etc)
4. methodName5. (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 <int, double, String, array> and returns <int, double, String, array, etc>
Takes parametersReturns return type
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)
Exam tip!Given a list of parameters, a method call needs to have corresponding argument list!
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;
… 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?
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)!
Converter Class with Stubs
public class Converter { public static double fahrenheitFromCelsius(double degC) { return 0.0; } public static double cmFromFeetInches(int ft, double in) { double result = 0.0; return result; }}
return statement is the last line of a method!
Naming Methods
Method names in mixed case capital letter for 2nd and subsequent words
The same as variable’s naming convention
Putting them together
public static returnType methodName(pType1 p1, pType2 p2) {
body...
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
Classes vs. Objects
Classes can be used right awayUtilities.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 datadifferent objects have different datamethods are mostly about that data
Exam tip!static methods!
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 orangeokButton = 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;
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”!
Java modifiers
Access modifiers public private
Non-access modifiers static final
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 staticConstant final
Constructors
Constructor “builds” the object gives a value to each of the instance variables
private String aNumber; // A00…
private String name; // Last, First
private int grade;// 0 .. 100
public Student(String a, String n, int g) { aNumber = a; name = n; 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.
… 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)
… 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
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) { aNumber = a; } else { aNumber = “(illegal)”; } 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
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 callspublic static boolean equalsTo(int a[], int b[])
int[] a = new int[len];int[] b = new int[len];if (ArrayOperations.equalsTo(a, b)) {}
Getters and Setters
Getters:public String getANumber() { return aNumber;}
Setters:public void setPctGrade(int newGrade) { if (0 <= grade && grade <= 100) { 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!Setters:
public!Anyone can change!
Return type!(usually) void!
Non-static!Each student has own
grade!Set the value (with some conditions)
this keyword
Text definition:
“Within a method definition, you can use the keyword this as a name for the object receiving the method call.”
… 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.
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
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)
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
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
… Assigning Student Numbers
Student s1, s2;
s1 = new Student("Akiyama, Yasushi",75);
s2 = new Student("Cooper, Ray",90);
System.out.println(s1.A_NUMBER);
System.out.println(s2.A_NUMBER);
Output:A00000001A00000002
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
}
… 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
toString() method
@Overridepublic String toString() { 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);
Arrays
Array Base Types
Arrays can be of any base type, any sizeint[] score = new int[600];double[] weight = new double[70];boolean[] answers = new boolean[10];String[] words = new String[5000];
…any type at allScanner[] 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!
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]; for (int i = 0; i < NUM_ITEMS; i++) 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;
Arrays Know Their Own Length
Array length public static final int MAX_WORDS = 200;… String[] word = new String[MAX_WORDS]; if (word.length != MAX_WORDS) {
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;)
Creating Arrays with Values
Create an array object by listing elementsint[] 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 laterarr = new int[]{13, 17, 19, 23};
2 3 5 7 11
Initialize.java
Average and Differences
// read and sum the numbersint[] 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 # sum += num[i]; // add it to sum}// calculate the averagedouble ave = (double)sum / (double)NUM_ITEMS;// print the difference from the average of eachfor (int i = 0; i < NUM_ITEMS; i++) { S.o.p((num[i] – ave));}
WeeklyTemps.java
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
Method to Sum an Array
Array comes from callerint[] n = new int[]{2, 3, 5, 7, 11};int addedUp = sumArray(n);
Method adds up its elementspublic static int sumArray(int[] arr) { int sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } return sum;}
ArrayMethod.java
Returning Arrays
Methods can return arrays return type is an array typepublic int[] dice(int howMany) { … }public String[] wordsFrom(String line) { … }
Like any other object-returning method, the object/array to be returned is newint[] result = new int[howMany];…return result;
ArrayReturn.java
Exercise
Be able to write: equalsTo subtract max min
from ArrayOperations.java
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.
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.