LEARNING OBJECTIVES: For algorithms in the context of a particular specification that involves String objects:

  • identify standard algorithms
  • modify standard algorithms
  • develop an algorithm

Java has many methods that are helpful when working with strings:

  • String .substring –> retrieves portion of a string
  • String .equals –> compares two strings
  • String .length –> returns length of a string
  • for Loop –> iterating through characters of a string



Finding a substring within a string

We can use the “window” method:

A “window” is created the same length as the substring. We then iterate through the main string in sections and compare to the substring

For example:

I T E R A T E

with substring “ERA”




public class StringFinder {
public static void main(String[] args) {
    String word = "iterate";
    String sub = "era";
    boolean found = false; // will be set to true once substring is found 

    for (int i = 0; i < word.length(); i++) { //iterating forwards: starting at first index (0) and going to the length of the word.. let's try word.length
        String portion = word.substring(i, i + sub.length());
        if (portion.equals(sub)) // make sure you use .equals!!
            found = true;
    }

    if (found)
        System.out.println("substring is found within string!");
    else
        System.out.println("substring is NOT within string");
}

}

StringFinder.main(null);

POPCORN HACK: Run the code.. what happened? How can we fix it?

Tell us below!



Another issue:

I T E R A T E

What if our substring was the word “RATE”? Note that RATE is at the end of the whole string

public class StringFinder {
    public static void main(String[] args) {
        String word = "iterate";
        String sub = "rate";
        boolean found = false;  
    
        for (int i = 0; i < word.length() - sub.length(); i++) { //make sure the comparison is <=
            String portion = word.substring(i, i + sub.length());
            if (portion.equals(sub)) 
                found = true;
        }
    
        if (found)
            System.out.println("substring is found within string!");
        else
            System.out.println("substring is NOT within string");
    }
    
    }
    
    StringFinder.main(null);
substring is NOT within string

HACKS

Create a algorithm similar to the one above. Except this time, use iteration to count the number of vowels within the main string.

HINT: Use the boolean expressions we have learned in previous lessons. Which would you use when comparing your “window” with multiple options of substrings?

public class VowelFinder {
    public static void main(String[] args) {
        String word = "sunflower";
        int counter = 0;  
    
        for (int i = 0; i < word.length(); i++) { 
            String portion = word.substring(i, i + 1);
            if (portion.equals("a") || portion.equals("e") || portion.equals("i") || portion.equals("o") || portion.equals("u")) 
                counter++;
        }

        System.out.println(counter);
    }
    
    }
    
VowelFinder.main(null);
3

Lesson 2 Draft:

5.3 - Documentation with Comments

REMEMBER: comments are ignored by the compiler and anything written in them won’t execute

  • they’re used for people to make code more readable.. allows them to understand what’s happening without having to go further into the code
  • improves communication between TEAMS
  • allows code to be maintained over years
  • prevents execution when testing alternative code

You are NOT required to write comments of AP Exam FRQs, but it is always a good habit

The types of comments:

1) Single line: // 2) Multiline: /* */ 3) Java Doc: /** * * */

/* 
    Programmer: 
    Date: 
    Purpose 
 */

public class Main {
    public static void main(String[] args) {
        // variables
        double length = 2.5;
        double width = 4;

        //.. and so on
    }
}


/** 
 * javadoc comments:
 * jkafhjdajhf
 * 
 * @author
 * @version 
 */

Javadoc is a tool that pulls any comments written in this format to make a documentation of the class in the form of a webpage

Javadoc also has tags (as shown above)

Preconditions: conditions that must be met before the execution of a code in order for it to run correctly

  • Will be written in comments for a method for most APCSA questions
  • it is assumed that these preconditions are true, we do not need to check!

Postconditions: conditions that must be met after the conditions has been executed (outcome, state of variables, ect)

  • Will be written in comments for a method for most APCSA questions
  • we do have to check to make sure these have been met
  • good way to get a summary of what you need to be doing
// EXAMPLE FROM AP CLASSROOM:

public class SecretWord {
    private String word;

    public SecretWord(String w) {
        word = w;
    }

    /** 
     * Precondition: parameter num is less than the length of word
     * Postcondition: Returns the string of the characters of word from the index hum to the end of the word followed by the characters of word from index 0 to num, not including index num. The state of word has not changed
     */

    public String newWord(int num)
    {
        //implementation not shown
    }
}

5.4 - Accessor Method

OUR GOAL: to define behaviors of an object through non-void methods NOT using parameters written in a class

REMEMBER: an accessor method allows other objects to access static variables

What is the purpose of an accessor method?

It allows us to safely access variables without other people being able to. Also called get methods or getters.

They’re necessary whenever another class needs to access a variable outside of that class.

// Example class 

public class Movie {
    // private instance variables
    private String name;
    private int runtime;

    // default constructor 
    public Movie() {
        name = "";
        runtime = 0;
    }

    // overloaded constructor:
    public Movie(String n, int c) {
        name = n;
        runtime = c;
    }

    // added ACCESSOR METHOD for each variable

    public String getName() { // header 
        return name; // returning a COPY of the private instance variables
    }

    public int getRuntime() {
        return runtime
    }
}

An accessor method must be:

  • public in order to be accessible
  • the return type must match the instance variable type
  • usually name of method is getNameOfVariable
  • should be NO PARAMETERS

POPCORN HACKS: write an accessor method for each of the instance variables:

public class Course {
    private String name;
    private String gradeLevel;
    private int period;
}

Let’s look at another example:

public class Sport {

    private String name;
    private int numAthletes;

    public Sport(String n, int num) {
        name = n;
        numAthletes = sum;
    }

    public String getName() {
        return name;
    }

    public int getNumAthletes () {
        return numAthletes;
    }
}


Can we print out information about an instance of this object?

public class Sport {
    private String name;
    private int numAthletes;

    public Sport(String n, int num) {
        name = n;
        numAthletes = num;
    }

    public String getName() {
        return name;
    }

    public int getNumAthletes() {
        return numAthletes;
    }

    public static void main(String[] args) {

        Sport volleyball = new Sport("volleyball", 12);

        System.out.println(volleyball);
    }
}

Sport.main(null);
REPL.$JShell$12$Sport@791e2d40

What output did we get?

The code outputs the Object class in the form of classname@HashCode in hexadecimal


Let’s try using the toString method:

  • returns a string when System.out.println(object) is called
  • no parameters
public class Sport {
    private String name;
    private int numAthletes;

    public Sport(String n, int num) {
        name = n;
        numAthletes = num;
    }

    public String getName() {
        return name;
    }

    public int getNumAthletes() {
        return numAthletes;
    }

    public String toString() { // toString method.. HEADER MUST BE WRITTEN IN THIS WAY
        return "Sport: " + name +"\nNumber of Athletes: " + numAthletes;
    }

    public static void main(String[] args) {

        Sport volleyball = new Sport("volleyball", 12);

        System.out.println(volleyball);
    }
}

Sport.main(null);
   

Sport: volleyball
Number of Athletes: 12