Java Programming Review – Part 1 PDF

Summary

This document is a Java programming review, covering concepts such as classes, naming conventions and syntax. It's likely part of a high school computer science course.

Full Transcript

Java Programing Review – Part 1 ICS4U1 CLASSES  All programming in Java is done inside “classes”.  The first line of any program is: public class NameOfClass {  NameOfClass is whatever you choose to name the class, and the name of the program. YOU...

Java Programing Review – Part 1 ICS4U1 CLASSES  All programming in Java is done inside “classes”.  The first line of any program is: public class NameOfClass {  NameOfClass is whatever you choose to name the class, and the name of the program. YOUR CLASS NAME MUST MATCH YOUR.JAVA FILENAME!  Not every class is a program. In order for a class to be a program it must include the main() routine which is defined by: public static void main(String[] args) { NAMING SYNTAX  In programming, we use names to refer to all kinds of things (variables, classes, subroutines), and there are rules that dictate how we come up with these names.  Syntax refers to rules that MUST BE FOLLOWED OR YOUR PROGRAM NOT COMPILE NAMING SYNTAX NAMES MUST BE:  1 or more characters  Begins with a letter or underscore “_”  Made up of some combination of letters, digits, underscores  Spaces are not permitted in a name  Capital letters and lowercase letters are distinct  There are certain words which have an alternate meaning and therefore cannot be used as names: public, static, if, else, while, etc…. NAMING CONVENTIONS  Conventions refer to rules that the programming community has decided to follow in order to maintain consistency  Names of classes begin with upper case letters  Names of variables and subroutines (we will learn about these later) begin with lower case letters  When a name is made up of several words, customary to capitalize each word except the first (except in the case of classes in which you capitalize all words)  Class = AddingTwoNumbers  Variable or a subroutine = addingTwoNumbers VARIABLES  When a name is used to refer to a piece of data stored in memory we call it a variable  Think of a variable as a box that will hold data, you can manipulate and/or change what is held in the box  So a variable may actually be referring to different values depending on which point you are at in the program ASSIGNMENT STATEMENT  To put data into a variable, you use an assignment statement: variable = expression;  Example: age = 17;  puts the value 17 in the variable age  Example: accountBalance = deposit + interest  puts the value of deposit + interest in the variable accountBalance  These values may change depending on what part of the program you are executing TYPES  A Java variable only holds a certain type of data PRIMITIVE TYPES:  byte, short, int, long - all hold integers, which one you use depends on the size of the integer  float, double - hold real numbers (decimal numbers), which one you use depends on size and accuracy  char – holds a single character from Unicode  boolean – holds logical value of true or false PRIMITIVE TYPES  byte: one byte -128 to 127  short: two bytes -32768 to 32767  int: 4 bytes -2147483648 to 2147483647  long: 8 bytes -9223372036854775808 to 9223372036854775807  There is no need to memorize these values! Usually int will be good enough. PRIMITIVE TYPES  float: up to 7 significant digits  double: up to 15 significant digits  For accuracy, stick with double for real numbers  Char: a single character, like A, $, or 4  Always surround a char with single quotes, ‘A’, so it is not confused with a variable STRINGS  A String is a sequence of characters  It is an object, rather than a primitive data type  However, it is an object that we use quite frequently so it’s important to know  String is expressed as a sequence of characters between quotes VARIABLE DECLARATION  Variable declaration statement: declares one or more variable and gives them names  You must declare a variable before you can use it! Example: int ageOfStudent; char middleInitial;  It is acceptable to declare a variable, and assign a value to it at the same time, i.e. int ageOfStudent = 15; OUTPUT  So far, we have used System.out.println() to print output on the screen.  System.out.println() – has one parameter, where the parameter is the value of any of the primitive types: int, double, float, long, Boolean, char, byte, short, or it can be an object of type String, or really any object  System.out.println(x), where x is any value of any type – it could even be an expression such as distance*time  System.out.println() – prints a carriage return () after it prints the output  System.out.print() – does not print a carriage return after it prints the output INPUT  There are multiple ways of reading user input into a program  Java 5.0 introduced a Scanner class which makes it a bit easier to obtain tokenized input from a user.  Scanner is a class found in the java.util package (must be imported!)  import java.util.*;  A scanner object must be instantiated first  Scanner input = new Scanner(System.in); SCANNER CLASS  With Scanner, input is done using functions. Common methods:  nextInt() //reads a value of type int  nextDouble() //reads a value of type double  nextBoolean() //reads a value of type boolean  nextLine() //reads an line of String input  next() // reads one String word ARITHMETIC OPERATORS  Addition, subtraction, multiplication, division  +, -, *, /  If the program asks the computer to combine values of different types, the computer will give the result in the more inclusive variable type for that operation, in BEDMAS order  For example, if asked to compute 20.1 + 10, the computer will convert 10 to 10.0 first, then add  this is called type conversion ARITHMETIC OPERATORS  When two numbers are combined, the answer will be of the same type  Be careful with division! When you divide two integers, the answer will always be an integer (the decimal part is discarded)  In order to avoid having this happen in cases like 4/3, change one of the numbers to a real number, i.e. 4.0/3 or 4/3.0  Be careful… 3/2*5.0 = 1*5.0 = 5.0, but 3/2.0*5= 1.5*5 = 7.5 ARITHMETIC OPERATORS  %  computes the remainder when one integer is divided by another  this is called modulo  For example, 7%2 is 1 INCREMENT AND DECREMENT  Adding 1 or subtracting 1 to a variable is a fairly common operation  For example: counter = counter + 1  Can accomplish the same thing using: counter++  Adding 1 to a variable is called incrementing  The same can be done with subtraction  For example: counter = counter – 1  Can accomplish the same thing using: counter--  Subtracting 1 from a variable is called decrementing BLOCKS Block: Groups together a sequence of programming statements. { statements }  Enclosed in curly brackets { }  You have probably noticed that the main subroutine is a block  When a variable is declared in a block, it is local to that block, meaning that when the block is finished executing, the memory allocated for that variable is discarded.  The scope of a variable is the part of the program in which the variable is valid. THE IF STATEMENT  If statement: tells the computer to take one of two branches depending on whether the value of a given Boolean expression is true or false. This is an example of a branching statement. if (boolean-expression) { statement } else { statement } THE IF STATEMENT  Here is an example of a program that determines if a moviegoer is old enough to see an R rated movie. Scanner input = new Scanner(System.in); System.out.println(“What is your age?”); int age = input.nextInt(); if(age 0) { // input is OK; jump out of loop System.out.println("Your answer must be > 0."); break; } } // end of loop // continue here after break The Random Class  How can use random numbers in programs?  simulations  games (i.e. rolling a dice, flipping a coin)  Similar to the Scanner class that we have been using, Java has a Random class that allows random numbers to be generated in programs  Must be imported like the Scanner class import java.util.*; Creating a Random Class Object  to create a Random class object, we must declare a new object in which to store it Random generator = new Random(); Object type Object being created Object name Using the Random Class  the Random class has built-in methods for generating random numbers  after creating a Random object named ‘generator’, we can generate random numbers as follows: Code Result generator.nextInt(int n); Returns an integer chosen at random from 0 to n-1 generator.nextDouble(); Returns a double chosen at random between 0.0 and 1.0 Example - Random Class // outputs 10 random integers chosen from 0-9 Random generator = new Random(); int randomValue; for(int i = 0; i < 10; i++) { randomValue = generator.nextInt(10); System.out.println(randomValue); } // end of loop Practice Activities 1) Create a dice rolling simulation program that produces two random numbers (the result of rolling two die), then asks the user if he/she would like to roll again. If the user says yes, then roll again, otherwise end the program. 2) Create a program that plays a guessing game with the user. The user guesses at an unknown random integer between 0 and 100 generated by the program. If the guess is not correct, the program tells the user whether the guess is too high or too low. At the end of the game, the program outputs the number of guesses it took to win. Java Programming Review – Part 3 ICS4U1 Methods  Also called subroutines  Recall that methods are just instructions for carrying out a task, grouped together, and given a name.  Somewhere else in the program, that method name can be used in place of a whole series of instructions.  When the computer encounters a method name, it executes all of the instructions associated with that method. Methods  methods are a key idea in Object Oriented Programming  methods simplify repetitive code by allowing code to be re-used  methods also help with modularity (dividing code into independent modules that could be independently tested) Black Box  A method is sometimes described as a “black box” because you can’t see what’s inside it when you call a method  Three rules for methods: 1. The interface of a method should be straightforward, well-defined, and easy to understand. 2. To use a method you shouldn’t need to know anything about its implementation(the inside), just its interface. 3. The code inside a of a method should not need to know anything about the larger system in which the method will be used. Methods  Every method must be defined inside a class.  A method in Java takes the form: () { } where:  visibility modifier – public or private method (more on this later)  return type – the data type (int, String, double, etc) of the value that the method returns  method name – name of the method (following variable naming convention)  parameter list – list of input values required by the method  implementing code – the code to be executed Visibility Modifier  the visibility modifier controls which classes can access the method  public – method can be accessed in other classes  private – method can only be accessed inside the class it is created in  static – method does not require instantiation of the class (i.e. method can be called without creating a class object) Return Type  the return type is the data type (i.e. int, String, double, etc) of the value that the method returns  Example:  the nextInt method in the Scanner class has a return type of int, which is why we assign the value as an int int number = input.nextInt();  if the method does not need to return a value the return type is set to: void Method Name  the method name follows the variable naming conventions: 1. it should be descriptive (e.g. nextInt, getAverage, etc) 2. there can be no spaces 3. must begin with a letter 4. the first letter of the first word is lowercase, and subsequent words are capitalized (e.g. nextInt) Implementing Code  the implementing code (the body) is the part of the method that uses the variables in the parameter list (if required) to perform a task  if the method has a non-void return type, then the final line of the implementing code must be return Parameter List  the parameter list is a description of the data values that the method needs to complete its task  Example:  Math.pow method requires two int values as a paramter (base and exponent)  the parameters in the method must be declared by naming the data type and creating a temporary variable name  variables declared in a parameter list are only valid while that particular method is running  if the method does not require parameters, empty brackets () are still required Example – method to find average  the following is a method which takes 3 test marks and returns the average as a decimal public static double getAverage(int mark1, int mark2, int mark3){ double avg = 0.0; avg = (mark1 + mark2 + mark3)/3; return avg; } Calling the Method  since the methods we are writing are in the same class as the main method, we do not need to create an object (e.g. Scanner input = new Scanner(System.in); )  the method can be directly called from within the main method by typing the name of the method  when a method is called, the actual values given in the parameter list are called arguments public static void main(String[] args){ double average = getAverage(74, 91, 82); System.out.println(average); } Putting it all together public class StudentAverages { public static void main(String[] args){ double average = getAverage(74, 91, 82); System.out.println(average); }// end of main method public static double getAverage(int mark1, int mark2, int mark3){ double avg = 0.0; avg = (mark1 + mark2 + mark3)/3; return avg; }// end of getAverage method }// end of class Example – method with no return value public class HelloWorld { public static void main(String[] args){ greeting(); }// end of main method public static void greeting() { System.out.println(“Hello World!”); System.out.println(“How are you doing?”); System.out.println(“I am doing great!”); }// end of greeting method }// end of class Practice Activities  Write a program called SumAndAverage to produce the sum of 1, 2, 3,….to an upperbound (e.g. 100), which you get from the user. Also compute and display the average using a method.  Write a program containing a method that returns the sum of the numbers between two integers, i.e. if the two integers are 5 and 9, then the sum would be the result of 5+6+7+8+9. Strings, Output, and Math Class ICS4U1 Converting Data Types  integer (int) values can be assigned to decimal variables, but not vice versa  Example: int i = 4; double j = 3.2; j = i; //type conversion, j = 4.0 i = j; // does not work Casting  decimal values can be made to “fit” into integers by casting  casting makes a decimal number into an integer by truncating (cutting off) the numbers after the decimal (it does not round)  Example: double j = 3.2; int i = (int)j; //casting, i = 3 double k = (double)i; //casting, k = 3.0 The Math Class  the Math class include use mathematical methods that can be used in programs Using the Math Class  methods can be called from the Math class directly  (i.e. do not need to create an instance of a Math class object like Scanner or Random in order to use the class methods) Code Result Math.abs(int x) Returns the absolute value of an integer x Math.abs(double x) Returns the absolute value of a double x Math.pow(double base, Returns the base raised to the exponent double exponent) Math.max(int a, int b) Returns the larger value of integers a and b Math.min(int a, int b) Returns the smaller value of integers a and b Math.sqrt(double x) Returns the square root of x Example – Math Class // outputs the absolute value, square root, quartic value (raised to exponent 4) of a given number Scanner input = new Scanner(System.in); System.out.println(“Enter a value: ”); double num = input.nextDouble(); System.out.println(“The absolute value is:“ + Math.abs(num)); System.out.println(“The square root is:“ + Math.sqrt(num)); System.out.println(“The quartic value is:“ + Math.pow(num, 4.0)); Strings  Strings are a class object which means that we can call methods on them that alter their contents and returns a results, and the original String remains unchanged  think of Strings as an array of char values, with index values that start at 0 up to the length of the String - 1  Example: String name = “Reyes”; 0 1 2 3 4 ‘R’ ‘e’ ‘y’ ‘e’ ‘s’ length  length() returns the length of a String  Example: String name = “Reyes”; System.out.println(name.length()); // prints 5 substring  substring(int start, int end) returns a portion of the String beginning at index ‘start’ and ending and index ‘end’ where the char at index ‘end’ is not included  Example: String name = “Reyes”; String end = name.substring(2, 5); System.out.println(end); // prints “yes” charAt  charAt(int index) returns the char value in the String at the specified index  Example: String name = “Reyes”; char end = name.charAt(4); System.out.println(end); // prints “s” indexOf  indexOf(char c) returns the first index of the given char found within the String  returns ‘-1’ if the given char is not found in the String  Example: String name = “Reyes”; System.out.println(name.indexOf(‘e’)); // prints 1 equals/equalsIgnoreCase  equals() is used to compare if two Strings are equal  equalsIgnoreCase() treats upper and lower case letters the same  Example: String name = “Reyes”; if (name.equalsIgnoreCase(“reyes”)) { System.out.println(“Same name!”); } Combining Output  ‘+’ symbol performs concatenation System.out.println(“The answer is:” + 8/2 + “kilometers”);  println will only print one String, therefore, you must concatenate  concatenation does not add spaces  Examples: Input Output “2” + “2” 22 “2 + 2” 2+2 2+2 4 Printing Special Characters Escape Sequence Output \n creates a new line \t inserts a tab (set of spaces) \\ inserts a backward slash “\” \‘ inserts a single quotation \“ inserts a double quotation Practice Activities 1. Write a program that asks the user for the length of two sides of a triangle (should check to ensure positive values only). The program will use a method to calculate the hypotenuse using the Pythagorean Theorem (a2 + b2 = c2) where ‘c’ is the hypotenuse. 2. Write a program that continually asks the user for a word, uses a method to eliminate all the vowels, and returns a String which is output to the screen. If the user enters ‘exit’, the program ends  Example: input: Reyes output: Rys Arrays ICS4U1 What is an Array?  an array is a variable that can hold many values  all arrays have a fixed size that specifies the number of values it can hold  the size of the array is set when an array is initialized  each data ‘slot’ in an array is called an element  each element in an array is accessed using an index or address Why use an Array?  arrays are useful for storing similar data that would otherwise be stored in large number of individual variables  for example, storing the phone numbers of every student in the school  instead of declaring 1000 different variables for each phone number, we can declare one array with 1000 elements Visualizing an Array  analogy: think of an array as a street with several houses which each has an address 0 1 2 3 4 … 48 49 50 51  the addresses of the houses start at 0 and go up by 1  what is the final address if the street had 100 houses? Visualizing an Array  an array is a variable, so it requires a name and data type 0 1 2 3 4 … 48 49 50 51 deckOfCards  all addresses in the array will have the same data type (i.e. if one index holds a String, then all will hold Strings) Declaring an Array in code  declaring an array is done similar to declaring any other variable String[] cards; Type of data to Name of the by stored in the array variable array Initializing an Array in code  initializing an array is where we give the array its size String[] cards; cards = new String; Size of the array  or declare and initialize an array in one line: String[] cards = new String; // an array with index from 0 to 51  in general, [] = new [array size]; Using an Array  an array can be used just like any other variable, we can:  assign values to it contents  perform operations on its contents  print its contents  we can only work with one address of the array at a time // assign a value to array index cards = “Ace of Spades”; cards = “Two of Spades”; // print the contents of index 0 System.out.println(“The first card is: “ + cards); // change the value at array index 0 cards = “Queen of Hearts”; Example - Arrays  the following is an example of an array used to store test scores: // declare and initialize the array int[] testScores = new int; testScores = 85; testScores = 100; testScores = 75; testScores = 87; testScores = 68; int sum = testScores+testScores+testScores+testScores+testScores; Looping through an Array  since an array holds multiple values, it is often useful to loop through the contents of an array  the starting index is always 0, but we need to know how high of an index to loop to  we can obtain the length of an array using the.length attribute  for example, the following prints the length of the ‘cards’ array // print 52 since the ‘cards’ array size is 52 System.out.println(cards.length); Looping through an Array  a for loop can be used to go through the contents of an array  the following loop sets each value of the array to be a “Joker” String[] cards = new String; for (int i = 0; i < cards.length; i++) { cards[i] = “Joker”; }  note the restriction i < cards.length  there would be an error if we try to access cards since the array goes from 0 to 51 Practice Activity 1  Write a program that asks the user for 4 courses and a final mark for each course. These values should be stored in parallel arrays (i.e. course and final mark share the same address for each array). Afterwards, your program should print the course with the highest mark and the course with the lowest mark.  Example output: Your highest mark was in Math (92%) Your lowest mark was in English (76%) Practice Activity 2  Write a program that creates an array with 50 random numbers between 1 and 100. Afterwards, ask the user for a number between 1 and 10. Your program should print all the numbers in the array that are divisible by the number that was input by the user. 2D Arrays ICS4U1 2D Arrays – An Array of Arrays  one dimensional (simple) arrays can be thought of as a list or a line  two dimensional arrays can be through of as a table or grid 2D Array – Declaration and Instantiation  2D arrays are declared like regular arrays, except with two coordinates [rows][columns] int[][] table = new int; //  you will need both references in order to access a specific element 2D Array – Example 2D Array – Initializer Lists String[][] salutation = { {“Mr.”, “Mrs.”, “Ms.”}, {“Reyes”, “Smith”} }; // Mr. Reyes System.out.println(salutation + salutation);  Like regular arrays, 2D arrays can also use initializer lists  The first list fills up the first array at salutation  The second list fills the array at salutation  Hence, the individual arrays do not have to be the same length 2D Array – Nested Loops  Techniques useful for 1D arrays can be transferred to 2D arrays  i.e. Nested loops to cover each element int sum = 0; for (int i = 0; i < table.length; i++) { for (int j = 0; j < table[i].length; j++) { sum = sum + table[i][j]; } } Uses of 2D Arrays  Games involving location-sensitive play – Board games, Battleship, tic-tac-toe  Displaying graphics on a screen (x and y coordinates)  Recording user-specific information for many users  Spreadsheets  Essentially, anytime there is more than one variable to keep track of Practice Activity  A magic square is a two-dimensional array of positive integers such that the sum of each row, column, and diagonal is the same constant. The following example is a magic square whose constant is 34:  Write a program that takes 16 integers as inputs. The program should determine whether or not the square is a magic square and display the result Array Lists ICS4U1 Array List  an array list is an object that functions like an array (a collection), but only handles elements that are objects themselves, but not primitives  to use array lists the following needs to be imported: import java.util.ArrayList;  an array list is instantiated without a size parameter: ArrayList list = new ArrayList();  qualifier limits the object that can be added to the list Arrays vs Array Lists Arrays Array Lists size of array cannot be have no defined size and changed once it is can be made bigger or instantiated smaller as necessary the size of an array must be can adjust the size an carefully kept track of to position of their elements avoid accidentally erasing as elements are removed or duplicating elements even from the middle of adding or removing items the list from the middle of an array requires careful management Arrays vs Array Lists Objects Only  array lists can only handle objects  we can get around this by “wrapping” primitive values (int, double, boolean) in “wrapper classes”  Wrapper Class:  object classes with names that match their data type  Examples: Integer, Double, Boolean, etc  adding primatives to a list will automatically cast them into these wrapper classes  e.g ArrayList list = new ArrayList(); list.add(1); // casts the 1 into an object of type Integer and adds it to the list Example – Array List ArrayList list = new ArrayList(); // creates Array List of Integer objects list.add(10); list.add(20); list.add(30); list.add(40); // casts 10, 20, 30, 40 into objects of type Integer and adds it to the list System.out.println(list); // prints [10, 20, 30, 40] list.remove(0); // removes element at index 0 list.remove(new Integer(20)); // removes 20 from list System.out.println(list); // prints [30, 40] Activity 1  Write a program that:  creates an ArrayList with 50 random numbers between 1 and 100  print the ArrayList  ask the user for a number between 1 and 10  remove all the numbers in the ArrayList that are divisible by the number that was input by the user  print the updated ArrayList Activity 2  Write a program that:  asks the user for 5 words and create an ArrayList of the 5 words  print the ArrayList  ask the user for a number for the maximum word length  remove all the words in the ArrayList that exceed the maximum word length that was input by the user  print the updated ArrayList Exception Handling ICS4U1 Exceptions  an exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions  these are technically objects that contain information about what went wrong exactly  an exception causes your program to end prematurely  this is generally not a good thing When Do Exceptions Occur?  exceptions can occur due to several reasons including:  bad math (dividing by zero)  referring to objects that do not exist (null pointer)  mismatching data types (i.e. user entering a decimal when an int was expected)  accessing array elements that are out of bounds Why Exceptions?  exceptions are a useful way to distinguish between bad things that happen to good code and bad code  allows for separating “Error Handling” code from “Regular” code Handling Exceptions  prevent exceptions from ever happening by using careful if-else conditions about parameters and input (what we currently do for ‘error checking’)  or use a ‘try-catch’ statement:  place the code that may cause an exception within try brackets  follow immediately with a catch(Exception e)statement with instructions on what to do if an exception occurs in what is being tried Example – Try-Catch Statement Scanner input = new Scanner(System.in); int num = 0; System.out.println(“Enter an integer:”); try { num = input.nextInt(); } catch (Exception e) { System.out.println(“That is not an integer.”); } // checks to ensure that an integer is entered by the user Example – Try-Catch Statement with Loop Scanner input = new Scanner(System.in); int num = 0; boolean correctInput = false; //boolean value used for checking //correct input while (!correctInput) { //loop until correct input entered try { System.out.println("Enter an integer: "); num = input.nextInt(); correctInput = true; //will not get here if exception is //thrown } catch (Exception e){ input.nextLine(); //let the scanner skip over the bad //input System.out.println("That is not an integer."); } //end of loop System.out.println("The integer you entered is: " + num); Activity 1  Write a program that:  creates an ArrayList with 50 random numbers between 0 and 9  print the ArrayList  ask the user for a number between 1 and 10  include exception handling for non-integers inputs  take the user provided number and divide by each value in the ArrayList with random numbers, store results in a ArrayList of Double objects  include exception handling for division by 0 (do not include result in ArrayList)  print the ArrayList with the division results Files: Input and Output ICS4U1 File Saving and Loading  information stored in variables are lost when the program ends  saving data to files stored on hard drives, DVD’s or other peripherals allows information to be re-accessed and loaded back into the variables  loaded data is viewed as an input stream of bytes and saved data is written to an output stream  important classes:  Scanner class (for loading input) [found in java. util package]  PrintWriter class (for saving output) [found in java.io package] Loading Files (Input)  the Scanner is instantiated with a File object parameter Scanner reader = new Scanner(new File(filename));  in the background, the Scanner object creates a FileInputStream object, with the file as a parameter FileInputStream stream = new FileInputStream(filename);  the Scanner can then “read” the file using the same methods as when reading terminal input (i.e. nextLine(), nextInt(), etc) Saving Files (Output)  the PrintWriter is instantiated with a File object parameter PrintWriter writer = new PrintWriter(new File(filename));  in the background, a FileOuputStream object is created with the file as a parameter FileOutputStream stream = new FileOutputStream(filename);  the PrintWriter can then “write” to the file using the print()or println()methods  the PrintWriter object must close()after the file is written or the file may be corrupted Exceptions  the IOExcpetion (from java.io) belongs to a category of exceptions referred to as “checked” exceptions  checked exceptions are checked at compile time and are of significant severity that Java requires their possibility to at least be acknowledged by the method that might produce it public static void main(String[] args) throws IOException { File Object  in order to instantiate the Scanner or the PrintWriter, the File must be given as a parameter Scanner reader = new Scanner(new File(“numbers.txt”));  the File parameter (numbers.txt) is either a pathname or the name of a file in the same working directory Example – PrintWriter PrintWriter writer = new PrintWriter(new File(“H:\\hello.txt”)); // creates PrintWriter object which opens a text file hello.txt for(int i = 0; i < 100; i++) { writer.println(“Hello “ + (i + 1)); // writes “Hello” in the text file 100 times } writer.close(); // close the text file Example – PrintWriter (hello.txt) Example – Scanner Scanner reader = new Scanner(new File(“H:\\hello.txt”)); // opens hello.txt file as an input int count = 0; String allLines = “”; // String which will take in text from file while(reader.hasNext()) { // loop until the end of the file String line = reader.nextLine(); // read line from file allLines = allLines + line + “\n”; // add line to allLines // read each line of the file count++; } System.out.println(“There are “ + count + “ \”hello\”s in the file.”); System.out.println(line); // print contents of file to terminal Activity 1  Write a program that asks the user how many random numbers from 1-100 they would like to record, and then saves an output file (output.txt) with that number of random numbers in it  include exception handling for non-integer inputs  Write a program that reads a text file (output.txt) with numbers and adds them to an ArrayList. Print out the ArrayList on the terminal along with the count and sum of the numbers in the file Searching Arrays ICS4U1 Search Searching an array is a common function in computer programs Generally, a search returns the index at which the searched value is located An example is the ‘indexOf’ method for strings Search algorithms differ depending on the type of the value being searched, as well as the array itself Linear Search – Unsorted A linear search loops through the elements of an unsorted array and compares each element to the search value For primitives (i.e. int, double, char), the == operator is used: public static int linearSearch(int[] a, int searchValue) { for (int i = 0; i < a.length; i++) { if (a[i] == searchValue) { return i; // returns index of value found } } return -1; // value not found }// end of method Linear Search – Unsorted For objects (Strings, etc.), the.equals() method is needed instead: public static int linearSearch(String[] a, String searchValue) { for (int i = 0; i < a.length; i++) { if (a[i].equals(searchValue)) { return i; // returns index of value found } } return -1; // value not found }// end of method The == operator is used with objects to check if the variables point to the same object, not if the variables are two separate equivalent objects Example String[] stringArray = {“Hi”, “there”, “Martin”}; // array of Strings int stringPos = linearSearch(stringArray, “Martin”); // returns index 2 Sorted Arrays Linear searching works well for small collections of data, but can become less efficient with large arrays If an array is sorted (e.g. by number (increasing) or by letter (alphabetically)) the search can be made much more efficient For example, looking for a name in a phone book – not every name needs to be looked at to find someone Binary Search A binary search processes a sorted array much more quickly by Checking if the value at the midpoint index of the array is the item searched for. If so, the search ends, but otherwise: If the midpoint value is less than the target value, then the midpoint becomes the new lower limit, and the new midpoint is considered, etc. If the midpoint value is more than the target value, then the midpoint becomes the new upper limit, and the new midpoint is considered, etc. Binary Searching numbers Binary Search Binary Search Here is a video which explains the Binary Search algorithm: https://www.youtube.com/watch?v=fDKIpRe8GW4 Binary searching an Alphabetical List An alphabetically ordered list can be binary searched using the String methods.compareTo(aString) and.compareToIgnoreCase(aString) s.compareToIgnoreCase(t) will return A negative value if s is alphabetically before (less than) t 0 if s is equivalent to t A positive value if s is alphabetically after (more than) t Binary Searching Object Arrays (Strings) Practice Activity 1 Write a program that finds a specified value in a given array using a linear search method create a method that implements a linear search using an array and a given value create an array of 100 random values between 1 and 50 ask the user for a value between 1 and 50 search the array using the linear search method and return the index of the first instance of the user’s value in the array Practice Activity 2 Write a program that finds a specified value in a given array using a binary search method create a method that implements a binary search using an array list of Strings and a given value read the file ‘words_alpha.txt’ into an array list of Strings ask the user for a word search the array list using the binary search method and return the index of the user’s word in the array Sorting Arrays ICS4U1 Sorting  Recall that Binary Searching is more efficient, but requires the array to be in order  Sorting algorithms rearrange arrays such that the elements in the array are placed in order  There are various sorting algorithms, we will look at the following:  Selection Sort  Bubble Sort  Insertion Sort Selection Sort  Places the array in ascending order  Main Idea:  For each index position, i, of the array, starting from 0  Find the smallest value from i to the end of the array (index of.length()-1)  Swap the smallest value into position i with the original index of the smallest value  Loop on to the next index position, i + 1, and repeat the algorithm Selection Sort  Here’s a video explaining the selection sort in more detail https://www.youtube.com/watch?v=g-PGLbMth_g Example – Selection Sort Example – Selection Sort Bubble Sort  Places the array in ascending order  Main idea:  Starting from index 0, compare each pair of adjacent elements (0 and 1)  For each pair, place the elements in the correct order (i.e. if the two elements are not in order, then swap them)  Move on to the next pair (1 and 0) and repeat the comparison and swap if necessary – only if a swap was made in the previous pass, otherwise done  After one pass through the array this way, the largest value in the array should be in the last position  Repeat the process from the beginning of the index, but do not include the last index (and second-last, third-last etc.) Bubble Sort  Here’s a video explaining the bubble sort in more detail https://www.youtube.com/watch?v=xli_FI7CuzA Example – Bubble Sort Example – Bubble Sort (Pseudocode) while (exchanges are still made) { loop through the array from start to finish if two adjacent elements are not in order swap elements } Example – Bubble Sort Selection Sort vs Bubble Sort  Selection is not very efficient, since every position requires the entire array to be searched  Bubble is more efficient because it can end early (i.e. if no exchange has been made in one pass, the array is assumed to be in order)  Bubble is therefore more efficient for arrays whose beginning elements are already in order and do not require movement  However, if the array is out of order from the beginning, the bubble sort is not any more efficient because it will not end early Insertion Sort  Places the array in ascending order  Main idea:  Starting at the second element (index of 1), save it as the variable in focus and compare the element with all the ones before it  If the element before it is less in value with the variable in focus, then move the element before into the next index and proceed backwards to the previous element and compare, etc.  If the element before it is not less in value, then insert the variable in focus at that place in the array  Compare to how you might draw a card from a deck and insert it into the right spot in order (i.e. you find the spot and move all the following cards down one position) Insertion Sort  Here’s a video explaining the insertion sort in more detail https://www.youtube.com/watch?v=JU767SDMDvA Example – Insertion Sort Example – Insertion Sort Practice Activity 1  Write a program that implements the Selection Sort algorithm  create an array of 50 random values between 1 and 50  print the unsorted array  sort the array using the selection sort algorithm  print the sorted array Practice Activity 2  Write a program that implements the Bubble Sort algorithm  create an array of 50 random values between 1 and 50  print the unsorted array  sort the array using the bubble sort algorithm  print the sorted array Practice Activity 3  Write a program that implements the Insertion Sort algorithm  create an array of 50 random values between 1 and 50  print the unsorted array  sort the array using the insertion sort algorithm  print the sorted array Modularity ICS4U1 Modular Programming  the concept in software development that aims to break up all the individual tasks of a program into independent modules (subprograms) that work together  this is one of the core concepts of object oriented programming  benefits of modular programming:  code reusability (i.e. less code duplication)  client-server relationship  easier to locate and fix errors  less intrusive when making changes (i.e. changes to individual modules) Classes and Objects  classes and their objects (instance of a class) are the main concepts that Java uses to achieve modularity  a class is a description of the attributes and behavior of a particular object  it is a template of an object (an abstract category)  an object is a collection of related attributes and behaviors.  it has an identity  it is an instance (or “working example”) of a particular class  Example: creating a Scanner class object to allow for user input from the keyboard “Student” Class  for example, the concept of a “student” is an abstract category  there are many students in our class  in one sense, they are individual (unique names, phone numbers, heights, weights, grades, likeability)  in another sense, they are all connected (they have similar attribute categories, and should be able to perform similar functions – writing tests, doing homework, sitting down)  you are all individual instances (objects) of a general type (class) Some Functions in the “Student” Class The Structure of a Class 1. name of the class (capital letter for each word) 2. instance (class) variables used by the object (instance) of the class 3. constructor method to instantiate the object 4. methods used by the class, and their method variables General Template for a Class Example – Student Class … more methods to follow Class Name  the first line of a class is usually  the “public” keyword indicates that the class is accessible to other client classes  the “extends” keyword defines the current class as a subclass of another superclass, which gives it access to the superclass’s methods  this is called inheritance (more of this later in the course) Instance Variables  the instance variables usually take the form example: private int myNum  the keyword private indicates the variables are only accessible to the object itself, and not to the client (users of the class)  this is called information hiding Constructor Method  the constructor method contains instructions for initializing the instance variables of a newly instantiated object  the name of the constructor method must match the name of the class exactly  there is no return type  there can be multiple constructors for a class, each accepting different parameters, and each initializing the variables in a different manner Example – Constructor Methods Class Methods  usually declared “public” (so that client classes can access them)  method descriptions usually take the form (as we do in our current programs)  except the constructor, which has no return type specified  methods generally fall into two categories:  mutators ( or “setters”) which set/change the value of variables  accessors (or “getters”) which get/return the value of variables (i.e. non-void methods) Class Methods – Local Variables  variables declared inside a method are referred to as local variables  they are for temporary storage, and are no longer available after a method finishes, unlike instance variables which exists for the lifetime of the instantiated object Class Methods – Return type  methods that return something (non-void) must have a return statement, which ends the method  the literal or variable following the return statement must match the return type of the method  there can be more than one return statement in a method toString()  by default, all objects have a toString() method which returns a String with the hashcode (hexadecimal) representation of the object  this method can an be overwritten for specific printing needs: Client Class  contains the “main” method  it is the class in which the object of the server class is instantiated  needs to be in the same package as the server class Example – Client Class (Creating Instance of Student Class) Practice Activity 1  Implement the class called Student (as described in the notes)  the instance variables of this class are  name (a String)  test mark 1 (an int)  test mark 2 (an int)  test mark 3 (an int)  include a constructor method and methods for accessing and modifying the variables as shown in the notes (see Methods table on Slide 5)  create a client class that includes the main method which creates an instance of the server class Student and includes a menu with following options (based on each method):  Add student’s name  Get student’s name  Add test mark  Get test mark  Get average  Get high mark  Print student info (i.e. toString() method Graphics ICS4U1 Introduction to Graphics Drawing  so far, all our Java programs have been console applications (i.e. input and output text on the terminal)  we will now look into the concept of drawing in Java and creating graphical user interfaces (GUIs) for our programs  a graphical user interface (GUI) allows the user to interact with a program with ‘events’ such as button clicks and check boxes, and the GUI will ‘listen’ to these events and handle them as required by the application Introduction to Graphics Drawing  Java GUI Toolkits  In Java the Graphics toolbox is inside the Abstract Windowing Toolkit (AWT)  AWT:  makes it possible to draw simple geometric shapes, print text, and position images within the borders of a component, such as a frame (a window) import java.awt.*;  Swing:  a more sophisticated and advanced Java GUI Toolkit  uses AWT to create operating system windows that are 100% compatible across platforms import javax.swing.*; Introduction to Graphics Drawing  JFrame:  an independent window that is the main window of an application  JPanel:  an invisible container for laying out other drawing components which can be added to a JFrame  also known as the “content pane”  components such as buttons and check boxes can be added to a JPanel Introduction to Graphics Drawing  JFrame and JPanel Introduction to Graphics Drawing  try coding this JFrame and JPanel: Introduction to Graphics Drawing  the output should be: Introduction to Graphics Drawing  JFrame methods Method Description setSize(width, height) Sets the size of the frame setLocation(x,y) Sets upper left corner of the frame setLocationRelativeTo(null) Sets location of frame centered on screen (when null is used) setVisible(true) Display the frame when set to true setDefaultCloseOperation Closes the frame (Jframe.EXIT_ON_CLOSE) pack() Automatically sets the frame size to hold the components of the frame add(panel) Adds panel to the frame Introduction to Graphics Drawing  JPanel methods Method Description add(component) Adds a component to the panel setLayout(layout) Sets the layout of the panel Introduction to Graphics Drawing  JLabel  allows for instructions or other information to appear in a GUI window  example: JLabel label = new Label (“Hello World!”); // create new label panel.add(label); // add the label to the content panel Introduction to Graphics Drawing  JLabel methods: Method Description setForeground(Color.RED); Sets the colour of the label to red setText(String n); Changes the text in the label Introduction to Graphics Drawing  JButton  a labelled, independent button that can be used in an application  a component that can be added to a JPanel  example: JButton button = new JButton("START"); panel.add(button); // add button to content panel Introduction to Graphics Drawing  ActionListener:  used when creating interactive components  for example, when a JButton is clicked, an event will be generated, and ActionListener ‘listens’ for this event and do ‘something’ Introduction to Graphics Drawing  try this code which creates a GUI Window class that has buttons: Introduction to Graphics Drawing  here is the client class with the main method to create the GUIWindow object: Graphics – Part 2 ICS4U1 Introduction to Graphics Drawing  in the previous lesson, we learned about:  creating a JFrame window  creating a JPanel content pane  creating a JLabel  creating a JButton  adding ActionListener to a JButton  in this lesson, we will explore:  creating a JCheckBox;  creating a JRadioButton; Introduction to Graphics Drawing  JCheckBox  a labelled, check box that can be used in an application  a component that can be added to a JPanel  example: JCheckBox option1 = new JCheckBox(“Option 1"); panel.add(option1); // add check box to JPanel Introduction to Graphics Drawing  try this code which updates the GUI Window class to include check boxes:  add the following instance variables: Introduction to Graphics Drawing  add the following code to the outputGUI()method: Introduction to Graphics Drawing  add the following code to the actionPerformed()method: Introduction to Graphics Drawing  when the client class with the main method is run, the following window will be generated: Introduction to Graphics Drawing  JRadioButton  a labelled, radio button that can be used in an application  a component that can be added to a JPanel  example: JRadioButton answer1 = new JCheckBox(“Answer 1"); JRadioButton answer2 = new JCheckBox(“Answer 2"); panel.add(answer1); // add radio button to JPanel panel.add(answer2); // add radio button to JPanel Introduction to Graphics Drawing  try this code which updates the GUI Window class to include radio buttons:  add the following instance variables:  the ButtonGroup object groups the radio buttons so only one button can be selected at a time Introduction to Graphics Drawing  add the following code to the outputGUI()method: Introduction to Graphics Drawing  add the following code to the actionPerformed()method:  this will print the output on the console and on the JPanel Introduction to Graphics Drawing  when the client class with the main method is run, the following window will be generated: Graphics – Part 3 ICS4U1 Introduction to Graphics Drawing  in this lesson, we will explore:  creating a JTextField; (for single-line text entry)  creating a JComboBox; (for drop-down menus) Introduction to Graphics Drawing  JTextField  another component that can be added to a JPanel  allows user to enter a text-based response  should include a JLabel ‘message’ to tell the user what to enter  example: JLabel label = new JLabel ("Enter a message: "); JTextField message = new JTextField(20); // 20 col text box content.add(label); content.add(message); Introduction to Graphics Drawing  try this code which updates the GUI Window class to include a text field with buttons:  add the following instance variables: Introduction to Graphics Drawing  add the following code to the outputGUI()method: Introduction to Graphics Drawing  add the following code to the actionPerformed()method:  the.getText() method will retrieve the text that was entered in the text field Introduction to Graphics Drawing  when the client class with the main method is run, the following window will be generated: Introduction to Graphics Drawing  JComboBox  a ‘drop-down’ box that allows the user to choose from a list of options from an array  a component that can be added to a JPanel  example: String[] subjects = {"Math", "English", "Science", "Art", "Comp Sci"}; JComboBox box = new JComboBox(subjects); content.add(box); Introduction to Graphics Drawing  try this code which updates the GUI Window class to include a drop-down menu:  add the following instance variables: Introduction to Graphics Drawing  add the following code to the outputGUI()method: Introduction to Graphics Drawing  add the following code to the actionPerformed()method:  the.getSelectedItem() method will take the selected item from the drop-down box and the.toString() method will convert it to a String that can be printed Introduction to Graphics Drawing  when the client class with the main method is run, the following window will be generated: Software Development Cycle ICS4U1 The Software Development Cycle  the Software Development Cycle is an outline of the major steps taken by programmers/software companies in developing software applications  the Software Development Cycle is used by all major software development companies The Software Development Cycle  the 6 steps in the cycle are: 1. Requirements Analysis 2. Design 3. Implementation 4. Testing 5. Software Release/Deployment 6. Maintenance The Software Development Cycle Step 1: Requirements Analysis  before designing software, the programmer must understand all the requirements of the software based on the specifications from the customer/end user  the requirements are listed using ‘shall’ statements  Example of requirements:  the program shall include a user menu  the program shall allow users to enter their name and phone number  the program shall calculate the tax based on the sub-total Step 2: Design  once the requirements are finalized, the program is designed using methods such as:  pseudo code  flow charts  these design documents allow for reviewing and updating the software design before it actually gets coded Step 2: Design  Flow Chart Symbols Step 2: Design  you can create flow charts using Microsoft Word, Google Docs, or free online flow chart creators such as https://www.draw.io/  sample flow chart: Step 3: Implementation  implementation involves writing the code in a specific programming language (such as Java)  different teams may be responsible for different methods of the program (i.e. modular programming) Step 4: Testing  after the code is written, it must be tested against the requirements to ensure all requirements have been met  test cases should be created to test each requirement  if requirements have not been met, the code must be updated and re-tested Step 5: Software Release/Deployment  after the software has been fully tested and requirements have been met, the software is released to the customer/end user Step 6: Maintenance  as the customer/end users are using the software application, they may find ‘bugs’ which the program should not be doing  the programmer/software company is responsible in providing software ‘patches’ to fix these unexpected bugs in the program The Software Development Cycle  for larger companies, entire departments are responsible for one of the steps in the cycle (i.e. one group will be responsible for the requirements, another group will implement the code, and another group will test)  communication is very important in sharing and passing of information from department to department  questions regarding the software development cycle are very common in job interviews for software companies

Use Quizgecko on...
Browser
Browser