AP Computer Science A 2nd Quarter Notes Table of Contents - section links - Click on the date or topic below to jump to that section Date: 11/9/2017 Aim: Binary Numbers (lesson 14) Number Systems Date: 11/14/2017 Aim: Base Conversion (lesson 14) Base10toBase2: Base10toBaseX: Date: 11/20/2017 Aim: Review Classes, Constructors, & Methods (Lesson 15) Classes, Constructors & Methods Date: 11/27/2017 Aim: Introduction to Arrays (Lessons 18 & 19) An ARRAY is - Declaration & Initialization of arrays: The Arrays class & its common methods: Date: 12/8/2017 Aim: Arrays Creating an object that has another object as one of its properties Date: 12/18/2017 Aim: Arrays: Insert, Delete, Min, Max Finding Min & Max elements: Inserting elements into a sorted array: Deleting elements from a sorted array: Enhanced For Loop (for-each) Date: 1/5/2018 Aim: Static Methods & Static Variables (Lesson 20) Method use so far: Using a static method: Using a static variable: Static Methods & Variables used to-date: Static relationships: Date: 1/16/2018 Aim: Wrapper Classes, File Input & Output (Lessons 21-25) Wrapper Classes: Two main uses: File Input & Output: File Input: File Output: Finding a File s Path (in Windows): Formatting Examples:
Date : 11/9/2017 Aim : Binary Numbers (lesson 14) Number Systems Humans: Computers: Base 10 (decimal) 10 fingers Symbols 0-9 Base 2 (binary) Transistors with 2 settings: off (0) / on (1) ALL SOFTWARE > Machine (binary) code Binary Bit = 1 binary digit Groups: Nibble = 4 bits Byte = 8 bits Kilobyte (KB) = 1000 bytes Megabyte (MB) = 1000 kilobytes Gigabyte (GB) = 1000 megabytes Terabyte (TB) = 1000 gigabytes Date : 11/14/2017 Aim : Base Conversion (lesson 14) Base10toBase2: What variables are needed? What type of loop? What is the loop control variable? What will cause the loop to stop? How is the remainder calculated? How is the quotient calculated?. Convert 13 base-10 to base-2 2 ) 13 13 base 10 = 1101 base 2. Convert 13 base-10 to base-16 16 ) 13 13 base 10 = D base 16 Base10toBaseX: What is different when converting to any other base? - Divide by the new base - Convert 2-digit remainders to a character (A - F)
Date : 11/20/2017 Aim : Review Classes, Constructors, & Methods (Lesson 15) Recall the following : public class Penguin{ private String name; public Penguin (...) { public return-type get () { public void set (params) { public String tostring () { // property; instance variable // constructor // accessor // mutator // tostring public class PenguinTester { public static void main (String args [ ]) { Classes, Constructors & Methods Class Property Modifier Behavior State Instance Variable Constructor method Accessor method Mutator method Local Variable - a blueprint for an object,defining its properties and behaviors (ie, car) - what the object has (ie, color, doors, mpg) - access outside of the class: public (yes) or private (no) - what the object does (ie, start, stop, fill up) - the combined values of all of an object s fields - declared outside of any method - relate to an instance of an object; ie an object s state private String color; - has a default value (0, null, etc.) - create objects using the blueprint public Car (); - retrieve information from the object public String getcolor ( ) { return color; - change information for the object public void setcolor (String c) { color = c; - defined inside a method - the scope is only within the body of that method - it must be initialized
Date : 11/27/2017 Aim : Introduction to Arrays (Lessons 18 & 19) An ARRAY is - - a container object that holds a fixed number of values of a single type - stored in memory as a contiguous block - given a set length when it is created - represented in java using brackets: int [ ] mynumarray = new int [10]; - Contiguous : next to / touching one another - Each element within an array is accessed by its numerical index - Index references begin with the number 0 - An array of length 10 has indices of 0-9 Declaration & Initialization of arrays: String[] flag1 = new String[5]; flag1[0] = A1 ; flag1[1] = B2 ; System.out.println(flag1[1]); String flag2[]={ C3, D4, E5 ; System.out.println(flag2[0]); char flag3[]=new char { a, b ; System.out.println(flag3[4]); >> IndexOutOfBounds Exception >> ArrayIndexOutOfBoundsException Length is a PROPERTY not a METHOD: int len = flag2.length; int len = flag2[0].length(); Arrays can be passed to methods, if the method has been written to accept one Different references to the same array String [] flag1 = new String { A, B, C ; String [] flag2 = flag1; // not a new array; points to the flag1 array []x vs. x[] GarbageCollector Physical versus logical size of an array Physical - number of elements that have been declared: i nt [] x = new int [5] ; Logical - number of elements that have been initialized: x[0] = 1; x[1] = 12 ;
The Arrays class & its common methods: Parsing / Splitting a string using a delimiter: String s = Hello. Goodbye. CUL8R ; String sp[]; sp = s.split(. ); //sp[0]= Hello, sp[1]= Goodbye, sp[2]= CUL8R Sorting elements within an array: int b[] = {104, 2, 19, 17, 34 ; // b[0]=104, b[1]=2, b[2]=19, etc. b[] 104 2 19 17 34 0 1 2 3 4 Arrays.sort(b); // b[0]=2, b[1]=17, b[2]=19, etc. b[] 2 17 19 34 104 0 1 2 3 4 Searching for an element in an array: int idx = Arrays.binarySearch(b, 109); Comparing length and contents of two arrays: boolean eq = Arrays.equals(x, y)); Date : 12/8/2017 Aim : Arrays Creating an object that has another object as one of its properties public class BankAccount { private String name; private double amount; public String tostring () { return... + name +... + amount; public class BigBank { private BankAccount acct; private char type; public String tostring () { return acct.tostring() + in an account type + type +. ; Note: In BigBank, acct is a BankAccount object; therefore acct.tostring() references the tostring method in the BankAccount class
Date : 12/18/2017 Aim : Arrays: Insert, Delete, Min, Max Min and Max W Q G A C L S D Z V U K P Insert A B C D G K L P Q S U V W Z Delete A B C D K L P Q S U V W Z Finding Min & Max elements: Declare & Initialize variables String min =, max = ; Traverse the array Compare each element to the variable if (letter[i].compareto(min) < 0) If it is lower (or higher) replace the variable s current value with the new one min = letter[i]; W Q G A C L S D Z V U K P Inserting elements into a sorted array: Traverse the array, continuing while the element is less than the new object while (letter[i].compareto(n) < 0) Store the index where the object belongs ni = i; Move to the right all elements after the correct index, starting at the end letter[i] = letter[i-1]; Add the new object letter[ni] = n; A B C D G K L P Q S U V W Z
Deleting elements from a sorted array: Traverse the array looking for the object if (letter[i].compareto(d) == 0) Store the index of the object di = i; Move to the left all elements after the correct index, starting at the index letter[i] = letter[i+1]; A B C D K L P Q S U V W Z Enhanced For Loop (for-each) for (int i = 0; i < letters.length; i++) { System.out.println (letters[i]); // for each String element in String [] letters for (String s : letters) { System.out.println(s); A B C D K L P Q S U V W Z
Date : 1/5/2018 Aim : Static Methods & Static Variables (Lesson 20) Static methods and variables, also known as Class methods and variables: These methods and variables can be used without first creating an object. Method use so far: public class Pet { private String animal; private int numpaws; public Pet(String a) {animal=a; public void says (String c) {System.out.println(c); public class MakePet { public static void main (String args[]){ Pet pet1 = new Pet( cat ); pet1.says( meow ); To access methods in the Pet class you must first have created a Pet object Using a static method: public class Pet { private String animal; private int numpaws; public Pet(String a) {animal=a; public static void says (String c) {System.out.println(c); // this method is now static public class MakePet { public static void main (String args[]){ Pet.says( meow ); // called from the class, not an object STATIC methods can be accessed by referencing the CLASS, not an OBJECT of the class Observation # 1 : The ability to use methods of a class without having to first create an object.
Using a static variable: public class Pet { private String animal; private static int numpaws;... public class MakePet { public static void main (String args[]){ Pet.numPaws = 4; // 4 paws Pet bird = new Pet ( bird ); // 4 paws bird.numpaws = 2; System.out.println(Pet.numPaws); // 2 Observation # 2 : When a static variable is set, it is set (or reset) for all occurrences of the class. Static Methods & Variables used to-date: main public static void main... Math.random() int rnum=math.random() * 5; Math.PI() double pi = Math.PI(); Arrays.sort Arrays.sort(aName,0,indx); Static relationships: Static methods can only reference other static methods and static variables Non-static methods can reference either static or non-static methods and variables Static variables can be constants: public static final double PI=3.14159;
Date : 1/16/2018 Aim : Wrapper Classes, File Input & Output (Lessons 21-25) Wrapper Classes: Boxing primitive data types into objects; Unboxing them from objects File I/O: Reading from / writing to data files Wrapper Classes: Primitive data types are not objects; they do not belong to any class Wraps a data type and gives it an object appearance Two main uses: 1. Convert simple data types into objects for when an object is needed 2. Convert (parse) Strings into data types Examples: Primitive Data Types Wrapper Classes String s = 100 ; int i = 8; double d1=10.0, d2=5.0; int Integer Integer.parseInt(s); Integer.toHexString(i); double Double Double.sum(d1, d2); Double.toString(d); boolean Boolean Boolean.parseBoolean(s); Click below for more information and methods: Integer Double Boolean
File Input & Output: Reading files from a disk, flash drive, etc. Reading files from the Internet Writing files to a disk, flash drive, etc. File Input: File Output: import java.io.*; import java.util.*; // for File, IOException // for Scanner public class FileTester { public static void main(string args[]) throws IOException { Scanner sf = new Scanner(new File("C:\\data.txt")); int indx = -1; String text[] = new String[100]; while(sf.hasnext()) { indx++; text[indx] = sf.nextline() ; sf.close(); import java.io.*; // for File, IOException public class WriteToFile { public static void main(string args[]) throws IOException { FileWriter fw = new FileWriter( C:\\Output1.txt,true); // add true to append to a file // leave it off to create a new file PrintWriter output = new PrintWriter(fw); output.print ( Four-score and ); output.println (7); output.println ( years ago. ); output.close( ); // close is very important. Data isn t fw.close( ); // accessible until files are closed. Finding a File s Path (in Windows): File Explorer > Navigate to the folder with the file > Click in the address bar > Copy the path > Paste the path in your code, in quotes > Type the filename after the path
Formatting Examples: To space Strings within a set number of characters, and left or right justify: String stringinfo = hello ; System.out.println(String.format("%-10s", stringinfo)); // %- left justify, % right justify // 10s allow 10 spaces for the string To format doubles to 1 decimal place: import java.text.decimalformat; // import format library DecimalFormat df=new DecimalFormat(".#"); // new DecimalFormat object double num = 99.5; // number with data type double System.out.println(df.format(num)); // print using DecimalFormat object