Advertisement
Guest User

Untitled

a guest
Jul 9th, 2017
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 16.55 KB | None | 0 0
  1. /*
  2.  
  3.           _/_/    _/_/_/          _/_/_/                                            _/_/_/            _/        _/_/    
  4.        _/    _/  _/    _/      _/          _/_/    _/_/_/  _/_/    _/_/_/        _/          _/_/_/          _/    _/  
  5.       _/_/_/_/  _/_/_/        _/        _/    _/  _/    _/    _/  _/    _/        _/_/    _/        _/      _/_/_/_/    
  6.      _/    _/  _/            _/        _/    _/  _/    _/    _/  _/    _/            _/  _/        _/      _/    _/    
  7.     _/    _/  _/              _/_/_/    _/_/    _/    _/    _/  _/_/_/        _/_/_/      _/_/_/  _/      _/    _/      
  8.                                                                _/                                                      
  9.                                                               _/                                                                             
  10.                                                        
  11.     AP Computer Science A -- In-Class Notes, Valley High School, 2010-2011
  12.     Taught by Dave Cochran, taken by Will Crichton
  13.    
  14.     These notes are best read in Notepad++ (search the interwebs if you've never heard of it) with Java syntax highlighting.
  15.     Not all concepts taught in class can be listed here, due to either the use of visual aids such as diagrams or the laziness of the author.
  16.     The author was gone for some of the lectures due to extracurricular activities, as noted in the comments.
  17.    
  18.     Font: JS Stick Letters
  19.     ___       __        ___     __   ___     __   __       ___  ___      ___  __  
  20.      |   /\  |__) |    |__     /  \ |__     /  ` /  \ |\ |  |  |__  |\ |  |  /__`
  21.      |  /~~\ |__) |___ |___    \__/ |       \__, \__/ | \|  |  |___ | \|  |  .__/
  22.     I. Object oriented programming
  23.     II. Basics of Java programming
  24.         a. Variables
  25.         b. Typecasting
  26.         c. Operators
  27.         d. If statement
  28.     III. Looping structures
  29.         a. Repeat-until
  30.         b. For loop
  31.     IV. Arrays
  32.         a. 1-D arrays
  33.         b. 2-D arrays
  34.         c. ArrayLists
  35.     V. Methods
  36.         a. Using methods
  37.         b. Declaring methods
  38.     VI. Classes
  39.         a. Client classes
  40.         b. Wrapper classes
  41.         c. Author classes
  42.         d. Example ATM class
  43.     VII. Recursion
  44. */
  45.  
  46.  
  47.  
  48. /*   __   __        ___  __  ___     __   __     ___      ___  ___  __      __   __   __   __   __                           __  
  49.     /  \ |__)    | |__  /  `  |     /  \ |__) | |__  |\ |  |  |__  |  \    |__) |__) /  \ / _` |__)  /\   |\/|  |\/| | |\ | / _`
  50.     \__/ |__) \__/ |___ \__,  |     \__/ |  \ | |___ | \|  |  |___ |__/    |    |  \ \__/ \__> |  \ /~~\  |  |  |  | | | \| \__>
  51.  
  52.     Objects are a data structure that contains methods (functions) to use on the data structure
  53.  
  54.     Inheritance -- you get to use all the method of your "super" (or parent) class
  55.     i.e. if your parent is an integer, then if you inherit the methods of an integer, then you can use them in your own class
  56.    
  57.     Encapsulation -- data security! By making methods "private", outside programs cannot access the values within it
  58.         Only way to acesss private methods is either A. writing them yourself or B. using public methods that access the private methods
  59.        
  60.     Polymorphism -- keeping "ways" of doing things similar
  61. */
  62.  
  63.  
  64.  
  65. /*   __        __     __   __      __   ___                            __   __   __   __   __                           __  
  66.     |__)  /\  /__` | /  ` /__`    /  \ |__        |  /\  \  /  /\     |__) |__) /  \ / _` |__)  /\   |\/|  |\/| | |\ | / _`
  67.     |__) /~~\ .__/ | \__, .__/    \__/ |       \__/ /~~\  \/  /~~\    |    |  \ \__/ \__> |  \ /~~\  |  |  |  | | | \| \__>
  68.  
  69.     Programs can be created from two perspectives:
  70.         1. client, which is other people's work (i.e. java.lang, java.util)
  71.         2. author, you -- the original code
  72.        
  73.     Everything is a CLASS
  74.         - client program always has the "main" method
  75.         - author program has no "main" method
  76.        
  77.     In Java, the class name and the file name are the same.
  78.    
  79.     Rules for naming variables are the same as BASIC, but now you can use reserved words (i.e. boolean or for)
  80.    
  81.     Public vs. Private — public variables can be accessed by anyone, whereas private variables are only accessed by the class
  82.    
  83.     Syntax for declaring classes: [public OR private] class [identifier] { }
  84.        
  85.     Syntax for declaring methods: [public OR private] [static?] [return type] [identifier] ( [params] ) { }
  86.    
  87.     Static means that it makes a memory location before execution that contains a SINGLE value
  88. */
  89.  
  90. public class HelloWorld {
  91.     public static void main(String[] args){
  92.         System.out.println("Hello, World!");
  93.     }
  94. }
  95.  
  96. /*
  97.     II-a. Variables
  98.    
  99.     Identifiers can be lots of things!
  100.         - Variable
  101.         - Array name
  102.         - Class name
  103.         - Method name
  104.        
  105.     Primitive data types (only a single value, no methods that come with it):
  106.         boolean - 1 byte = false/true
  107.         char - 2 bytes (unicode)
  108.         int - 4 bytes, ±2^31
  109.         double - 8 bytes, ±1.8 * 10^308
  110.         ——————
  111.         byte - 1 byte, ±128
  112.         short - 2 bytes, ±32767
  113.         long  - 8 bytes, ±2^63
  114.         float - 4 bytes (single), ±3.4 * 10^38
  115.        
  116.     How to declare a variable: [type] [identifier]
  117. */
  118.  
  119. int intX = 50;
  120. double dblAverage = 0.3;
  121. boolean boolTest = true;
  122. char chrLetter = 'F';
  123. int intA, intB, intB = 5;
  124.  
  125. /*
  126.     II-b. Typecasting
  127.  
  128.     Scope - part of the program in which the value is valid
  129.     Declaring a value inside a set of braces (i.e. a for loop, function) means it can only be accesed from within that set of braces
  130.    
  131.     Assignment statement: [identifier] = [expression]
  132.         addition +
  133.         subtraction -
  134.         multiplication *
  135.         division /
  136.         remainder %
  137.         math.pow (function for exponentiation)
  138.  
  139.     Typecasting — to change the primitive type of a result
  140. */
  141.  
  142. int intX = 8 / 3; // intX now = 2
  143. double dblY = 8 / 3; // dblY = 2
  144. double dblY = 8 / 3.0; // dblY = 2.67.
  145.  
  146. double dblY = (double) (8/3); // dblY = 2.0
  147. double dblZ = (double) 8 / 3; // dblZ = 2.67
  148.  
  149. // Output: use the nice little System class
  150.  
  151. System.out.println("Hello, World!"); // prints a whole line (inserts \n character)
  152. System.out.print("Howdy, Earth!"); // just prints it, keeps going on same line
  153.  
  154. /*
  155.     II-c. Operators
  156.    
  157.     Expresion Operators
  158.    
  159.     greater than            is      >
  160.     less than               is      <
  161.     greater than/equal to   is      >=
  162.     less than/equao to      is      <=
  163.     equal                   is      ==
  164.     not equal               is      !=
  165.     and                     is      &&
  166.     or                      is      ||
  167.     not                     is      !
  168.  
  169.     Not operator distributes... so !(a || b) is !a && !b
  170.    
  171.     a+=b    same as     a = a + b
  172.     a-=b    same as     a = a - b
  173.     a*=b    same as     a = a * b
  174.     a/=b    same as     a = a / b
  175.     a%=b    same as     a = a % b
  176.     a++     same as     a = a + 1 (++a similar, but evaluates the 1 first?)
  177.     a--     same as     a = a - 1
  178. */
  179.  
  180. boolean a;
  181. int x, y;
  182. a = x < y;
  183.  
  184. /*
  185.    
  186.     II-d. If statements
  187.        
  188.     You don't necessarily need braces, but it's required for multiple statements.
  189.    
  190.     if ( condition )
  191.         statement;
  192.        
  193.     if ( condition ){
  194.         statement1;
  195.         statement2;
  196.         statement3;
  197.     }
  198.    
  199.     if ( condition )
  200.         statement1;
  201.     else
  202.         statement2;
  203.        
  204.     if ( condition ){
  205.         if ( condition2 ){
  206.             statement1;
  207.         }
  208.     } else {
  209.         statement2;
  210.     }  
  211. */
  212.  
  213. if ( bIsTrue ){
  214.     bIsTrue = !bIsTrue;
  215.     System.out.println( "The boolean is true! (but now it's false)" );
  216. }
  217.  
  218.  
  219.  
  220. /*        __   __   __          __      __  ___  __        __  ___       __   ___  __  
  221.     |    /  \ /  \ |__) | |\ | / _`    /__`  |  |__) |  | /  `  |  |  | |__) |__  /__`
  222.     |___ \__/ \__/ |    | | \| \__>    .__/  |  |  \ \__/ \__,  |  \__/ |  \ |___ .__/
  223.    
  224.     Repeat-Until:       While:          For:
  225.         Init                Init            Init
  226.         Increment           Step            Step
  227.         Body                Body            Body
  228.         Step                Increment       Increment
  229.         Exit                Exit            Exit
  230.    
  231.     While loop syntax:
  232.    
  233.     while( condition )
  234.         statement;
  235. */
  236.  
  237. while( x == true ){
  238.     y++;
  239.     a *= b + c;
  240. }
  241.  
  242. /*
  243.     III-a. Repeat-until
  244.    
  245.     Repeat-Until loop syntax:
  246.    
  247.     do {
  248.         statement;
  249.     } while ( condition );
  250. */
  251.  
  252. do {
  253.     a %= b * c;
  254.     System.out.println("Hello, World!");
  255. } while ( y == true && d == false );
  256.  
  257. /*
  258.     III-b. For loop
  259.    
  260.     For loop syntax:
  261.    
  262.     for ( init; step; increment ){ code; }
  263. */
  264.  
  265. for( int i=0; i<10; i++ ){
  266.     things;
  267. }
  268.  
  269.  
  270.  
  271. /*        __   __            __  
  272.      /\  |__) |__)  /\  \ / /__`
  273.     /~~\ |  \ |  \ /~~\  |  .__/
  274.    
  275.     IV-a. 1-D arrays
  276.    
  277.     Arrays are objects (not primitive types). They hold multiple variables. In Java, arrays can only hold values of a specific type (i.e. int)
  278.    
  279.     Declaring an array:
  280.     TYPE IDENTIFIER []
  281. */
  282.  
  283. int aNumber[];
  284. aNumber[5] = 10;
  285.  
  286. int num1[], num2[];
  287. int [] num1, num2;
  288.  
  289. int values[] = new int[15];
  290.  
  291. int numbers[] = { 19, 23, 74, 58, 6 };
  292. String names[] = { "John", "Mary", "Fred" };
  293.  
  294. for( int intLoop = 0; intLoop < names.length - 1; intLoop++ )
  295.     System.out.println(names[intLoop]);
  296.    
  297. /*
  298.     IV-b. 2-D arrays
  299.    
  300.     I missed this day's lecture.
  301.    
  302.     As you would expect, 2-D arrays are just arrays of arrays. Simple BASIC stuff. Main thing different is how to initialize.
  303.    
  304.     TYPE IDENTIFIER[][] = new TYPE[BOUND1][BOUND2]
  305. */
  306.  
  307. int NumArray[][] = new int[5][4];
  308. int Array1D[] = new int[4];
  309. Array1D = NumArray[1]; // Note: this assignment duplicates the values in NumArray[1] into Array1D, it doesn't create a pointer (meaning changing NumArray[1] does not change Array1D)
  310. int[][] changeArray( double[][] myArray ){ } // Declaring a method with both a 2-D return type and passing 2-D array as a parameter
  311.  
  312. /*
  313.     IV-c. ArrayLists
  314.    
  315.     I missed this day's lecture.
  316.    
  317.     ArrayLists are basically arrays which don't have a defined length.
  318.     Also, ArrayLists are strictly objects, so you treat them like you would any other object (use methods on them).
  319. */
  320.  
  321. import java.util.ArrayList;
  322. ArrayList<Object> list = new ArrayList();
  323. list.add("Hello!");
  324. list.add(new Double(5.2));
  325. System.out.println(list.size());
  326. // Common methods: add, get, indexOf, remove, size
  327.    
  328.    
  329.    
  330. /*         ___ ___       __   __   __  
  331.      |\/| |__   |  |__| /  \ |  \ /__`
  332.      |  | |___  |  |  | \__/ |__/ .__/
  333.      
  334.     V-a. Using methods
  335.    
  336.     Classes have constructors, and then methods
  337.     To use have methods, you do: identifier.method(PARAMETERS);
  338.    
  339.     String class! You should know the following methods:
  340.     int length()
  341.     String substring(int from, int to)
  342.     String substring(int from)
  343.     int indexOf(String str)
  344. */
  345.  
  346. String word = "ABCDEFGHIJK";
  347. word.length() // is 11
  348. word.substring(8) // is IJK
  349. word.substring(5,8) // is FGH
  350. word.indexOf("CDE") // is 2
  351.  
  352. /*
  353.     V-b. Declaring methods
  354.    
  355.     Declaration syntax:
  356.         [private OR public] [return-type] [identifier] ( [parameters] ){ }
  357.    
  358.     Methods are generally going to be public.
  359.     Return types will be of a primitive type (boolean, int, etc.), an object type (Integer, String, etc.), or a void type (returns nothing)
  360.     Parameters are set with ([type] [identifier], [type] [identifier], ...)
  361.    
  362.     Remember ByVal and ByRef? Parameters in Basic were passed either by creating a copy of the value or pointing to the original value.
  363.     In Java, all primtitve values are passed by value -- a duplicate is made.
  364.     All object parameters are passed by reference.
  365. */
  366.  
  367. public double AveFind( int[] numArray ){
  368.     double dReturn = 0;
  369.     for(int i=0;i<numArray.length;i++) dReturn += numArray[i];
  370.     return dReturn / numArray.length;
  371. }
  372.  
  373.  
  374.  
  375. /*   __             __   __   ___  __  
  376.     /  ` |     /\  /__` /__` |__  /__`
  377.     \__, |___ /~~\ .__/ .__/ |___ .__/
  378.    
  379.     VI-a. Client classes
  380.    
  381.     These classes often come in packages -- i.e. java.lang, java.util, java.text
  382.    
  383.     Rather than grabbing outside code every time you use it, Java allows us to establish a link to packages to use in the rest of the program.
  384.     This is done through the use of the "import" statement.
  385. */
  386.  
  387. import java.text.*; // imports all of java.text
  388.  
  389. /*
  390.     java.text is used to format the OUTPUT of values, like numbers and such.
  391.     It does not affect the value itself, but rather how it appears in the console -- i.e. converting numbers to dollars and cents.
  392.    
  393.     Useful function: "format"
  394. */
  395.  
  396. import java.text.DecimalFormat;
  397.  
  398. DecimalFormat moneyFormat = new DecimalFormat("0.00");
  399. String moneyAnswer = moneyFormat.format( 32.5255 ); // 32.53
  400.  
  401. /*
  402.     VI-b. Wrapper classes
  403.    
  404.     Wrapper classes change a primitive type into an object.
  405.    
  406.     Generally, we use the wrapper classes Integer and Double.
  407.     More specifically, you'll use the toString and intValue/doubleValue methods in those classes.
  408.     These are useful for storing and retrieving primitive types in object arrays.
  409. */
  410.  
  411. Double dValue = new Double(5.00);
  412. dNum = 3.0 * dValue.doubleValue();
  413.  
  414. /*
  415.     VI-c. Author classes
  416.    
  417.     Classes are like cars, except less flashy and they don't use gasoline. They're vehicles for the values and methods you want to use.
  418.     Difference between classes you've made so far is there's no "main" method, meaning the class is not executable by itself.
  419.    
  420.     Classes are divided into two areas, the "private" section and the "public" section.
  421.     The private sector contains values and methods only accessible by the class itself -- encapsulation
  422.         Generally, the private sector contains data (i.e. your credit card number or PIN number)
  423.    
  424.     The public sector can be accessed by anyone. It has:
  425.         Constructors -- how you tell the compiler that you want to create a space in memory for this object
  426.             A default constructor initalizes all variables to nothin'.
  427.             You can have multiple constructors with different parameters (i.e. passing an int or a String for some reason)
  428.         Accessors -- how you access data, typically begin with "get", i.e. obj.getValue();
  429.         Modifier -- change the data in the object, typically begin with "set", i.e. obj.setValue(param)
  430.         Overload -- take an existing symbol or method and change its execution
  431.        
  432.     For this class, you write three programs for each class-based project.
  433.         1. The class itself -- the class, variables, methods, etc.
  434.         2. The tester program -- test EVERY SINGLE method in the class for errors
  435.         3. The client program -- whatever you're trying to accomplish by using this class
  436. */
  437.  
  438. // The author class
  439. public class Fraction {
  440.  
  441.     // Private variables
  442.     private int myNumerator, myDenominator;
  443.    
  444.     // Private methods
  445.     private Fraction reduce(){
  446.        
  447.     }
  448.    
  449.     // Constructors
  450.     public Fraction(){
  451.         myNumerator = 0;
  452.         myDenominator = 1;
  453.     }
  454.    
  455.     public Fraction(int a, int b){
  456.         myNumerator = a;
  457.         myDenominator = b;
  458.     }
  459.  
  460.     public void fracOutput(){
  461.         System.out.println(myNumerator + "/" + myDenominator);
  462.     }
  463.    
  464.     public void setNumerator(int a){
  465.         myNumerator = a;
  466.     }
  467.    
  468.     public void setDenominator(int a){
  469.         if ( a == 0 ) throw new Error("Denominator cannot be set to zero");
  470.         myDenominator = a;
  471.     }
  472.    
  473.     public Fraction add(Fraction x){
  474.         return new Fraction(
  475.             myNumerator * x.myDenominator + myDenominator * x.myNumerator,
  476.             myDenominator * x.myDenominator
  477.         );
  478.     }
  479. }
  480.  
  481. // The tester class
  482. public class FracTester {
  483.     public static void main(String[] args){
  484.         Fraction x = new Fraction();
  485.         m.fracOutput();
  486.        
  487.         Fraction n = new Fraction(2,3);
  488.         n.fracOutput();
  489.        
  490.         m.setNumerator(3);
  491.         m.fracOutput();
  492.     }
  493. }
  494.  
  495. /*
  496.     VI-d. Example ATM class
  497.    
  498.     To log in to an ATM, you scan your card and enter your PIN. The ATM uses some fancy math to find your bank account based on your card number.
  499.     This process of creating card numbers from bank accounts is known as "hashing", which is the use of math operation(s) on a value to determine a second value.
  500.    
  501.     In this case, both your PIN number and account number are five digit prime numbers, and your card number is the two multiplied together.
  502.    
  503.     Things your ATM should do:
  504.         Login
  505.         Deposit
  506.         Withdraw
  507.         Balance summary
  508.         Transfer
  509.         Logout
  510.         Add account
  511.        
  512.     Data members:
  513.         Account number
  514.         PIN number
  515.         Login boolean?
  516.         Checkings/savings
  517.         Personal info (name, address, city, state, zip)
  518.        
  519.     Constructors:
  520.         Default, zero for all values
  521.         Assign all values
  522.        
  523.     Accessors:
  524.         Get checking
  525.         Get savings
  526.         Get login info (account #, PIN #)
  527.        
  528.     Modifiers:
  529.         Withdraw (watch for insufficient funds)
  530.         Deposit
  531.         Transfer
  532. */
  533.  
  534. /*   __   ___  __        __   __     __      
  535.     |__) |__  /  ` |  | |__) /__` | /  \ |\ |
  536.     |  \ |___ \__, \__/ |  \ .__/ | \__/ | \|
  537.    
  538.     Recursion is the reverse of iteration (iteration is looping, where you go from small --> large).
  539.     In recursion, you go from large to small.
  540.    
  541.     Rules for recursion:
  542.         1. Must step the recursion
  543.         2. The problem MUST become "simpler"
  544.        
  545.     Famous recursive sequence: Fibonacci sequence. Each term in the sequence is the sum of the two preceding it.
  546.     1, 1, 2, 3, 5, 8, 13, 21...
  547.     To get the 75th term,
  548.    
  549.     Issues with recursion:
  550.         1. Takes a lot of memory. Recursive methods call themselves within themselves (i.e. running method A runs method A again).
  551. */
  552.  
  553. public int getFibo(int n){
  554.     if( n == 1 || n == 2 ) return 1;
  555.     return getFibo(n - 1) + getFibo(n - 2);
  556. }
  557.  
  558. getFibo(4); // return getFibo(3) + getFibo(2)
  559.             // getFibo(3) = getFibo(2) + getFibo(1) = 1 + 1
  560.             // return 2 + 1 = 3;
  561.            
  562. public int getFacto(int n){
  563.     if( n == 1 ) return 1;
  564.     return n * getFacto(n - 1);
  565. }
  566.  
  567. getFacto(4); // return getFacto(3) * 4;
  568.              // getFacto(3) = getFacto(2) * 3 = getFacto(1) * 2 * 3 = 1 * 2 * 3;
  569.              // return 1 * 2 * 3 * 4;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement