×
Log in to StudySoup
Get Full Access to USF - COP 251 - Study Guide - Midterm
Join StudySoup for FREE
Get Full Access to USF - COP 251 - Study Guide - Midterm

Already have an account? Login here
×
Reset your password

usf cop

usf cop

Description

School: University of South Florida
Department: Computer Programming
Course: Programming Concepts
Professor: Schinnel small
Term: Spring 2017
Tags: Arrays, methods, OPP, class, Drivers, toString, Accessors, Mutators, and static
Cost: 50
Name: COP 2510 Study Guide
Description: These notes cover the new stuff learned and what will be tested on for the Lab Exam/Midterm that's on April 21st. You should also consider using past homework as well. Topics covered for Lab Exam 3 will be on Arrays, Methods, OPP, Classes and Drivers, toStrings, Accessors and Mutators, and Static Variables.
Uploaded: 04/16/2017
22 Pages 137 Views 1 Unlocks
Reviews



❖ How is a static variable different from an instance variable?




❖ What are the values of the following statements?




Why use void methods?



COP 2510 Week 9 - Void Methods: Intro to Array Quick task The following methods are overloaded: Public static int subtract (int num1, int num2) { Return num1 - num2; } Public static int subtract (int num1, int num2, int num3) { Return num1 - num2 - num3; } Public static double subtract (double num1, double num2) { Return num1 -Don't forget about the age old question of psychology uf
Don't forget about the age old question of unconditioned reinforcement
If you want to learn more check out muscular system study guide
Don't forget about the age old question of in the ___________, electrons are ejected from the surface of a metal exposed to light of a certain minimum frequency.
We also discuss several other topics like physics 140
Don't forget about the age old question of Question: How does the presence of wolves influence the population of elk and aspen?
num2; } Methods will be used for the following statement: ❖ System.out.println Recall: Method - a group of statements that are collectively given a name. Methods may be a value returning or void. A value returning method returns a value after the method is called (invoked). A void method does not return a value after a method is invoked. Why use void methods? ❖ Since void method doesn’t return a value, you may wonder why it is useful. ❖ A void method is still appropriate for defining a group of statements to a task ❖ Values can be “returned” to main using output statements instead Return Statements in void methods? ❖ You CANNOT use a return statement in void method to return a value ❖ You can use a return statement to exit a method ➢ E.g if (denom == 0) { System.out.println(“Not allowed.”); Return; } ❖ If you attempt to use a return statement without a clause it results in a syntax error. INTRODUCTION TO ARRAYS ❖ An array is an ordered list of values.➢ Entire array has a single name ➢ Each value has a numeric INDEX ➢ Array of size N is indexed from zero to N-1 ❖ In Java, arrays are objects that must be instantiated. ➢ The name of the array is an OBJECT REFERENCE VARIABLE. Declaring Arrays - The scores array could be declared as: “Int[] scores = new int[10]; ❖ This type of variable scores is “int[]” ❖ The reference variable scores is set to a new array object that can hold 10 integers. ❖ Java provides two ways to declare arrays; Int [] grades; Int grades[]; ❖ The first is consistent with other types of declarations ❖ Declared type is explicit if array brackets are associated with element type ❖ Other examples of array declarations ➢ Int[] weights = new int[2000]; ➢ Double[] prices = new double[500]; ➢ Boolean[] flags; Flags = new boolean[20]; ➢ Char[] codes = new char[1750]; Accessing Array Elements ❖ To reference a particular value or element, use the array name followed by the position or index in brackets ➢ For Example, the expression: scores[2] refers to the value 94 (3rd value in array) ❖ An array element can be assigned, used for calculation or printed: ➢ Assigned → Scores[2] = 89; ➢ Calculation → Scores[0] = Scores[0] + 2; ➢ Printed → System.out.println(“Top = “ + scores[5]); ❖ FOR loops are very effective for manipulating the contents of an array. ❖ Recall: FOR loops are useful when you know EXACTLY how many times you need to repeat a process ❖ The size of an array provides this information.Output Public class BasicArray { //----------------------------------------------------------------- // Creates an array, fills it with various integer values, // modifies one value, then prints them out. //--------------------------------------------------------- Public static void main(String[] args) { Final int LIMIT = 15, MULTIPLE = 10; Int[] list = new int[LIMIT]; // Initiate the array values For (int index = 0; index < LIMIT; index++) List[index] = index * MULTIPLE; list[5] = 999; // change one array value // Print Values For (int index = 0; index < LIMIT; index++) System.out.print(list[index] + “ “); } } Arrays: FOR vs FOR-EACH loop ❖ You can use a variation of the FOR loop called the for-each loop: ➢ for (int value : list) System.out.print(value + “ “); ❖ The above is equivalent to ➢ For (int index = 0; index < LIMIT; index++) System.out.print(list[index] + “ “); Array Index and Bounds Checking ❖ Once an array is created, it has a fixed size ❖ An index used in an array reference must specify a valid element, i.e. value must be in range from 0 to N-1. ❖ The Java interpreter throws an “ArrayIndexOutOfBoundsException” if an array index is out of bounds. ❖ Example: if an array “codes” can hold 100 values, it can be indexed from 0 to 99.❖ The following will cause an exception to be thrown: ➢ For (int index=0; index < 100; index++) Codes[index] = index * 50 + epsilon; ❖ Known as an “off by one” error ❖ Each array has a public constant called “length” that stores the size of the array. ❖ It is referenced using the array name. ❖ Note: length holds the number of elements, not the largest index. ❖ EXAMPLE: - for (int index = 0; index < list.length; index++) System.out.print(list[index] + " "); Initializer Lists ❖ An initializer list can be used to fill an array in one step. ❖ Values are delimited by braces, and separated by commas. ❖ Examples: ➢ int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; Char[] letterGrades = {‘A’, ‘B’, ‘C’, ‘D’, ‘F’}; ❖ Note that when an initializer list is created: ➢ NO SIZE value is specified ➢ The new operator is not used ❖ The array size is determined by the number of items in the list. ❖ Initializer lists can only be used in the array declaration. Two-Dimensional Arrays (2D Arrays) ❖ A Two-Dimensional array can be thought of as a table of elements, with rows and columns. ❖ In Java, a 2D array is an array of arrays ❖ 2D arrays are declared by specifying the size of each dimension separately ➢ Int [] [] table = new int[12][50]; ❖ An element is referenced using two index values ➢ Value = table[3][6] ❖ The array stored in one row can be specified using one index ➢ Table[3]: the array of elements table [3] [0], Table [3] [1], …, table[3][49] ❖ Use nested loops to manipulate a 2D array ➢ For (int row = 0; row < table.length; row++) For (int col=0; col < table[row].length; col++) table [row][col] = row * 10 + col; Multidimensional Arrays ❖ An array can have many dimensions ❖ Each dimension subdivides the previous one into a specified number of elements. ➢ For each dimension add another nested loop!❖ Each dimension is an array of array references, so arrays within one dimension can be of different lengths ➢ Each dimension has its own length constant Arrays vs ArrayList ❖ Chapter 5 mentions ArrayList class ❖ Part of the java.util package ❖ To instantiate: ArrayList<String>Band = new ArrayList <String> (); ---- Week 12 - Arrays and Methods How to declare the following arrays – An array of 100 integers called people • int[]people = new int[100]; – An array of 5000 floa9ng point values called weights • double[]weights = new double[5000]; – A two-dimensional integer array called chart with 10 rows and 15 columns • int[][]chart = new int[10][15]; ❖ What are the values of the following statements? ➢ Height[1] = 61 ➢ Height [2] + Height[5] → 70 + 69 = 139 ➢ Height [2+5] = 73 ➢ Height.Length = 11 Height: 69, 61, 70, 74, 62, 69, 66, 73, 79, 62, 70 ARRAYS AND METHODS ❖ A array can be passed to the method. ❖ You would need the following: ➢ An array declared as a formal parameter (in the method header). ➢ An array declared as an actual parameter (within the main method).import java.util.Scanner; public class ArrayMethodExample { public static void main(String[] args) { Scanner input = new Scanner(System.in); double[] list2 = new double[10]; System.out.print("Enter 10 double values: "); int i = 0; while (i < list2.length) { List2[i] = = input.nextDouble(); i++; } System.out.println("The average is " + average(list2)); } public static double average(double[] array) { double sum = 0; for (int i = 0; i < array.length; i++) sum += array[i]; return sum / array.length; } } - Java also allows you to RETURN an array. - This is allowed because you actual return a reference to an array (considered one entity).import java.util.Scanner; public class ReverseArray { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter 10 integers: "); int[] myList = new int[10]; for (int i = 0; i < myList.length; i++) myList[i] = input.nextInt(); reverse(myList); for (int i = 0; i < myList.length; i++) System.out.print(myList[i] + " "); } Public static int[] reverse(int[] list) { For (int i = 0, j = list.length - 1; i < list.length / 2; i++, j--) { Int temp = list[i]; List[i] = list[j]; List[j] = temp; } Return list; } } ----- Lecture 03/30/17 → OPP, Classes and Methods Recall: Object-Oriented Programming uses classes, objects and methods as basic programming components. These components help us - Organize a large problem into small modules - Design an intricate program - Find and remove errors→ Classes Recall: Classes serve as blueprints for objects, aka they represent a concept. An object created from that class realizes that concept. ❖ Objects have ➢ State: defined by attribute values ➢ Behavior: Defined by operations A class can contain data declarations and method declarations. Example: Import java.text.NumberFormat; Public class Account { Private final double RATE = 0.035 Private long accNumber; Private double balance; Private String name; // Set up account Public Account(String owner, long account, double initial) { Name = owner; acctNumber = account; Balance = initial; } // deposit Public double addInterest() { Balance += (balance * RATE); Return balance; } // withdraws specified amount Public double withdraw(double amount, double fee) { Balance = balance - amount - fee;} // Adds interest Public double addInterest() { Balance += (balance * RATE); Return balance; } //Returns the current balance. Public double getBalance*( { Return balance; } // Returns a one-line description public String toString() { NumberFormat fmt = NumberFormat.getCurrencyInstance(); return (acctNumber + "\t" + name + "\t" + fmt.format(balance)); } } Example - Driver Programs ❖ A driver program drives the use of other more interesting parts of a program. ❖ Driver programs are used to test other parts of the software. ❖ Example: The transactions class contains a MAIN method that drives the use of the ACCOUNT class, exercising its services. Transactions.java Public class Transactions { // Creates some bank accounts and get service Public static void main(String[] args) { Account acc1 = new Account(“Ted Murphy”, 72354, 102.56); Account acc2 = new Account(“Jane Smith”, 69713, 40.00);Account acc3 = new Account(“Edward Demsey”, 93757, 759.32); acc1.deposit(25.85); Double smithBalance = acct2.deposit(500.00); System.out.println(“Smith balance after deposit: “ + smithBalance); System.out.println(“Smith balance after withdrawal: “ + acc2.withdraw (430.75, 1.50)); acct1.addInterest(); acct2.addInterest(); acct3.addInterest(); System.out.println(); System.out.println(acct1); System.out.println(acct2); System.out.println(acct3); } } To run the Bank Account Example: ❖ Place Account.java and Transactions.java in the same folder ❖ Compile both Account.java and Transactions.java ❖ Run Transactions.java only. (Account.java has no main method) → Constructors, and Instance Data ❖ A constructor is a special method that is used to set up an object when it is initially created. ❖ Constructors has the same name as the class. ❖ Programmers do not have to define a constructor for a class: Each class has a DEFAULT CONSTRUCTOR that accepts no arguments. Example: NOTE - no return type specified in the header, not even void. Common Error - put a return type on a constructor, making it a REGULAR method with the same name as the class. Public Account(String owner, long account, double initial) { Name = owner;acctNumber = account; Balance = initial; } Instance Data - Objects share the method definitions but each object has its own space. Account acct1 = new Account(“Ted Murphy”, 72354, 102.56); Account acct2 = new Account(“Jane Smith”, 69713, 40.00); ❖ Classes declare the type of the data, but does not reserve memory space for it. ❖ Whenever an ACCOUNT object is created, a NAME variable is created. ❖ Instance Variables (which are declared at class level) exists as long as the object exists. → ENCAPSULATION ❖ We can take one of two views of an object: ➢ Internal: The details of the variables and the methods of the class that defines it. ➢ External: The services that an object provides and how the object interacts with the rest of the system. ➢ From the external view, an object is an encapsulated entity, providing a set of specific services. ■ These services define the interface to the object ➢ One objects (or client) may invoke the interface methods of another object, which manages the instance data. ❖ NOTE: While a client may request the services of another object, the former does not have to be aware of how those services are achieved. ❖ We should make it difficult, if not impossible for one object to access another object’s variables directly. That is, an object should be SELF-GOVERNING. ❖ Think of an encapsulated object as a black box, whose inner workings are hidden from the client. → Visibility Modifiers ❖ In Java, encapsulation is achieved through the use of visibility modifiers. ❖ A modifier is a Java reserved word that specified particular characteristics of a method of data. ➢ E.G. final to define constants. ❖ Java has three visibility modifiers: public, private, and protected ➢ The protected modifier involves inheritance ❖ Members of a class that are declared with public visibility can be referenced anywhere. ❖ Members of a class that are declared the private visibility can be referenced only within that class.❖ Members declared without a visibility modifier have default visibility and can be referenced by any class in the same directory. ❖ Example: Public ➢ Public class withdraw(double amount, double fee) { Balance = balance - amount - fee; Return balance; } ❖ Example: Private ➢ Private final double RATE = 0.035; Private long acctNumber; Private double balance; Private String name; ❖ Public variables violates encapsulation because they allow the client to modify values directly. ❖ Instance variables should be declared with private visibility ❖ Constants may have public visibility which allows it to be used outside the class. ❖ Public constants does not violent encapsulation because its value cannot be changed (the client can access it). ❖ Methods that provide the object’s services are declared with public invisibility so that they can be invoked by clients ➢ Public methods are also called service methods ❖ A method created to assist a service method is called a support method. ➢ Since support methods are not intended to be called by a client, it should be declared with private visibility. → Data Scope ❖ The scope of the data is the area in a program in which that data can be referenced (used). ❖ Data declared at the class level can be referenced by all methods in that class. ❖ Data declares within a method can only be used within a method. ➢ This is known as a local data. Locals ❖ The formal parameters of a method create automatic local variables when the method is invoked. ❖ When the method finishes, all local variables are destroyed. ➢ Int add(int num1, int num2){ Int sum = num1 + num2; Return sum; } → More on Methods: toString, Getters, and Setters. toString ❖ The toString method returns a character string that represents the object in some way. ❖ It is called automatically when an object is concatenated to a string or when it is passed to the println method. ❖ It is good practice to define a toString method for a class. Example: When these lines are executed: - System.out.println(acct1); - System.out.println(acct2); - System.out.println(acct3); toString is used: Public String toString() { NumberFormat fmt = NumberFormat.getCurrencyInstance(); Return (acctNumber + “\t” + name + “\t” + fmt.format(balance)); } Accessors and Mutators ❖ Since instance data is private, a class usually provides services to access and modify data values. ❖ Accessor methods return the current value of a variable ➢ AKA getters; name gets the form of getX where X represents the value. ❖ Mutator methods change the value of a variable ➢ AKA Setters; name takes the form of setX. ❖ Accessor Example: ➢ Public double getBalance() { Return balance; } ❖ Mutator Example:➢ Public void setFaceValue(int value) { faceValue = value; } → WEEK 13A ← STATIC MODIFIER ● Recall: A static method is one that can be invoked through its class name, instead of through an object of that class. ● Example: Methods of the MATH class: ○ Result = Math.sqrt(25); ● Variables can be static as well ● Determining if a method or variable should be static IS an important design decision. ● Static methods and variables are declared using the static modifier. ● It “associates the method or variable with the class” rather than with an object of that class. ● Static methods are also called CLASS METHODS. ● Static variables are also called CLASS VARIABLES. Static Variables ❖ A static variable is shared among all instances of a class. ➢ private static int count = 0; ❖ If a variable is declared as static, “only one copy of the variable exists.” ❖ Memory space for a static variable is created when the class is first referenced. ❖ All objects instantiated from the class share its static variable. ❖ Important that changing the value of a static variable in one object changes it for all others. ❖ How is a static variable different from an instance variable? ➢ An instance variable is a variable declared within a class, but not inside a method. ➢ When an object of that class is created, each object has its own version and memory space of the variable. ➢ Remember: only one copy of a static variable exists for all objects of that class. ❖ How is a static variable different from a local variable? ➢ A local variable is a variable declared inside a method. ➢ Memory space for a local variable is only allocated when the method is referenced. ■ A local variable in a method cannot be static. ➢ Memory space for a static variable is allocated when the class is referenced.❖ Can a constant be static? ➢ Sure! ➢ Constants are VARIABLES whose value/content cannot be changed, thanks to the FINAL modifier. ➢ Since the value can’t be changed, there might as well be only one copy of it across all objects of the class. Static Methods ❖ Why have static methods? ➢ The methods in the MATH class perform basic calculations based on values passed as parameters, ➢ No good reason to create an object just to request those services. ❖ Why is the main method in Java static? ➢ “The main method is static so that it can be executed by the Java interpreter without creating an object that contains main.” ➢ Recall that the Java interpreter translates the code into the target language (machine language) and executes the instructions of that code. ❖ Since static methods do not operate in the context of a particular object, they cannot reference instance variables. ➢ Remember instance variables are only created when an object is created. ❖ However, a static method can reference static variables or local variables. Example of Static Modifier: Slogan.java public class Slogan { private String phrase; privatestatic intcount=0; //staticvariable //----------------------------------------------------------------- // Constructor: Sets up the slogan and counts the number of // instances created. //----------------------------------------------------------------- public Slogan(String str) { phrase = str;count++; } // Returns this slogan as a string. Public String toString() { Return phase; } // Returns the number of instances of this class that have been created. Public static int getCount() { Return count; } } SloganCounter.java - DRIVER PROGRAM Public class SloganCounter { // Creates several Slogan objects and prints the number of objects created. Public static void main(String[] args) { Slogan obj; Obj = new Slogan(“Remember the Alamo.”)’ System.out.println(obj); Obj = new Slogan(“Don’t Worry. Be Happy.”): System.out.println(obj); Obj = new Slogan (“Live Free or Die.”); System.out.println(obj); Obj = new Slogan(“Write Once, Run Anywhere.”); System.out.println(obj); System.out.println(); System.out.println(“Slogans created: “ + Slogan.getCount()); }} Output: Remember the Alamo. Don’t Worry. Be Happy. Live Free or Die. Talk is Cheap. Write Once, Run Anywhere. Slogans created: 5 The THIS reference ❖ The “this” reference allows an object to refer to itself. ❖ That is, the “this” reference, used inside of a method, “refers to the object through which the method is being executed.” ❖ “THIS” is a reserved word in Java. ❖ Supposed the “THIS” reference was used inside a method called tryMe: Private int num; Public void tryMe() { This.num++; } ❖ tryMe invoked as follows: obj1.tryMe(); (In the first innovation, the THIS reference refers to obj1). obj2.tryMe(); (In the second, it refers to obj2) ❖ The THIS reference can be used to distinguish instance variables of a class from corresponding method parameters with the same names. Consider: the constructor for the account class (Chapter 4) was written as: Public Account (String owner, long account, double initial) { Name = owner; acctNumber = account; Balance = initial; } Remember: Variables on lft were private members of the class. ❖ Using the THIS reference, the constructor could be written as: Public account (String name, long acctNumber, double Balance) { This.name = name;This.acctNumber = acctNumber; This.balance = balance; } ❖ This approach eliminates the need to come up with different, yet equivalent names. LECTURE 04/11/17 Week 14 Lecture File Input and Output (File I/O) ❖ Java provides several classes for reading data from a file and writing to a file. ❖ To read data from a file you can use: ➢ Scanner class ➢ File class ❖ To write data to a file you can use: ➢ PrintWriter class ❖ File must be opened ➢ This creates a connection to file and the program ❖ Data is then read or written to the file. ❖ File must be closed after the program is finished using it. ➢ This prevents corruption or loss of data. Input File - File that a problem reads from. - Data stored in the file serves as input Output File - File that a program writes to. - Program stores output in the file File formats: text (common) or binary Reading from a file. ❖ You will need to import the Scanner and File classes ➢ java.util.Scanner; ➢ java.util.io*; ❖ You will need to include a THROWS exception clause ➢ Any method that uses a Scanner object to read a file must have a THROWS IOException clause in its header. ➢ Public state void main (String [] args) Throws IOException ❖ You create a File object and pass the name of the file as a string to the constructor. ➢ File inputfile = new File (“Numbers.txt”);❖ You create a Scanner object and pass the reference of the file object as an argument to the constructor. ➢ Scanner scan = new Scanner(inputfile); ➢ Scanner fileScan = new Scanner(new File(“urls.inp”)); ❖ Use the Scanner class’ nextLine method to read a line from the file. ➢ Use nextInt for ints etc. ❖ Use the Scanner’s hasNext method to determine if there is more data to read. ➢ While (scan.hasNext()) { String name = scan.nextLine(); } ❖ When you’re done, use the Scanner’s close method to close the file. ➢ scan.close(); ❖ Tip: Make sure the file exists and can be found ➢ Create a copy of the file and place it in the same directory as your Java files. ❖ Text File contents: ➢ Hudson ➢ Tunde ➢ Bryan ➢ Petra ➢ Peaches ➢ Tammy ❖ Public class FileRead { Public static void main(String[] args) throws IOException { // open the file. File inputfile = new File(“MyFriends.txt”); Scanner scan = new Scanner(inputfile); // read lines from the file until no more are left While (scan.hasNext()) { // Read next name. String friendName = scan.nextLine(); // Display the last name read. System.out.println(friendName); }// Close the file scan.close(); } } Writing to a File ❖ Once again you will need to import the Scanner and File classes. ❖ You will also need to include a throws exception clause ➢ Any method that uses a PrintWriter object must have a throws IOException clause in its header. ❖ You create a PrintWriter object and pass the name of the file as a string to the constructor. ➢ PrintWriter outfile = new PrintWriter(“Movies.txt”); ➢ String filename = “Movies.txt”; PrintWriter outfile = new PrintWriter (filename); ➢ Warning: If the file you are opening with the PrintWriter object still exists, it can be overwritten. ❖ Use the PrintWriter’s print and println methods to write data to the file. ➢ outfile.println(movie); ❖ Close the file ➢ Outfile.close; ❖ Writing To A File - EXAMPLE // This program writes data to a file. import java.util.Scanner; // Needed for the Scanner class import java.io.*; // Needed for the File class public class FileWrite {  public static void main(String[] args) throws IOException  {  String movie; // for movie name  int numMovies; //Number of movies //For keyboard input  Scanner scan = new Scanner(System.in);  //Get number of movies  System.out.print("How many movies will you enter? "); numMovies = scan.nextInt(); scan.nextLine(); // get newline character [Enter] // Open the file. PrintWriter outfile = new PrintWriter("Movies.txt"); // Get data and write to the file  for (int i = 1; i <= numMovies; i++)  {  // Get name  System.out.print("Enter movie name: ");  movie = scan.nextLine();  // Write to the file  outfile.println(movie);  }  // Close the file.  outfile.close();  } }Exception ❖ When something unexpected happens in a Java program, an EXCEPTION is thrown. ❖ An exception is an object that describes an unusual or erroneous situation. ❖ A program can process an exception in 3 ways: ➢ Not at all - program terminates abnormally ➢ Handle the exception where it occurs ➢ Handle the exception at another point in the program ❖ We thrown an exception so that it can be caught and handled by another part of the program. ❖ (We also do this as exception handling is to be covered in more advanced courses :)) ❖ An error is also represented as an object in Java, but usually represents an unrecoverable situation and should not be caught. ❖ We use the keyword THROWS to insert a throws clause and add the name of the expected exception. ❖ SCANNER and PrintWriter objects can encounter Input/Output issues like “file not found” and “disk full” so they throw an IOException.

Page Expired
5off
It looks like your free minutes have expired! Lucky for you we have all the content you need, just sign up here