Skip to the content.

Homework for Calling Instance Methods

Example Class:

// Suppose we have a class:
public class Dog {
    private String name;
    public Dog(String name) {
        this.name = name;
    }
    public void bark() {
        System.out.println(name + " says: Woof!");
    }
}

// To use it:
Dog d = new Dog("Fido");  // create an instance
d.bark();                 // call the instance method on d

Popcorn Hack #1

  • Add another property to the dog class for breed.
  • Add another method to the dog class that prints “My dog name is a breed!”
  • Create a new object of this class and call the method.
// Work by Rohan Bojja

public class Dog {
    String name;
    int age;
    String breed;

    // Constructor
    public Dog(String name, int age, String breed) {
        this.name = name;
        this.age = age;
        this.breed = breed;
    }

    // Method to make the dog bark
    public void bark() {
        System.out.println(name + " says Woof!");
    }

    // Method to get the dog's info
    public String getInfo() {
        return "Name: " + name + ", Age: " + age + ", Breed: " + breed;
    }
}

// To use it:
Dog d = new Dog("Fido", 3, "Labrador");  // create an instance
d.bark();
System.out.println(d.getInfo());
Fido says Woof!
Name: Fido, Age: 3, Breed: Labrador

Example Class 2:

public class Counter {
    private int count;
    public void add(int x) {
        count += x;
    }
    public int getCount() {
        return count;
    }
}

// Use it:
Counter c = new Counter();
c.add(5);
int val = c.getCount();  // returns 5

Popcorn Hack #2

  • Add on to the previous counter class and add three more methods for subtraction, multiplication, and division.

  • Call all five methods outside of the class.

// Work by Rohan Bojja
public class Counter {
    private int count;    
    // Constructor
    public Counter() {
        this.count = 0;
    }
    
    // Method to increment the count
    public void increment() {
        count++;
    }
    
    // Method to decrement the count
    public void decrement() {
        count--;
    }
    
    // Method to multiply the count by a given factor
    public void multiply(int factor) {
        count *= factor;
    }
    
    // Method to divide the count by a given divisor
    public void divide(int divisor) {
        if (divisor != 0) {
            count /= divisor;
        } else {
            System.out.println("Error: Division by zero");
        }
    }
    
    // Method to get the current count
    public int getCount() {
        return count;
    }
    
}

// Use it:
Counter c = new Counter();
c.increment();
c.increment();
c.decrement();
c.multiply(3);
c.divide(2);
System.out.println(c.getCount());
1

MC Hacks

Question 1

Consider the following class:

public class BankAccount {
    private double balance;
    
    public BankAccount(double initialBalance) {
        balance = initialBalance;
    }
    
    public void deposit(double amount) {
        balance += amount;
    }
    
    public double getBalance() {
        return balance;
    }
}

Which of the following code segments will compile without error:

A)

BankAccount.deposit(50.0);
double total = BankAccount.getBalance();

B)

BankAccount account = new BankAccount(100.0);
account.deposit(50.0);
double total = account.getBalance();

C)

BankAccount account = new BankAccount(100.0);
double total = account.deposit(50.0);

D)

BankAccount account;
account.deposit(50.0);
double total = account.getBalance();

E)

double total = getBalance();
BankAccount account = new BankAccount(total);

Question 2

What is printed as a result of executing the following code?

public class Rectangle {
    private int length;
    private int width;
    
    public Rectangle(int l, int w) {
        length = l;
        width = w;
    }
    
    public int getArea() {
        return length * width;
    }
    
    public void scale(int factor) {
        length *= factor;
        width *= factor;
    }
}

Rectangle rect = new Rectangle(3, 4);
rect.scale(2);
System.out.println(rect.getArea());

A) 12

B) 24

C) 48

D) 96

E) Nothing is printed; the code does not compile

Question 3

Which of the following best describes when a NullPointerException will occur when calling an instance method?

A) When the method is declared as void

B) When the method is called on a reference variable that has not been initialized to an object

C) When the method’s parameters do not match the arguments provided

D) When the method is called from outside the class

E) When the method attempts to return a value but is declared as void

Question 4

Which of the following code segments will NOT compile?

public class Temperature {
    private double celsius;
    
    public Temperature(double c) {
        celsius = c;
    }
    
    public double getFahrenheit() {
        return celsius * 9.0 / 5.0 + 32;
    }
    
    public void setCelsius(double c) {
        celsius = c;
    }
}

A)

Temperature temp = new Temperature(0);
System.out.println(temp.getFahrenheit());

B)

Temperature temp = new Temperature(100);
temp.setCelsius(25);

C)

Temperature temp = new Temperature(20);
double f = temp.getFahrenheit();

D)

Temperature temp = new Temperature(15);
int result = temp.setCelsius(30);

E)

Temperature temp = new Temperature(0);
temp.setCelsius(100);
double f = temp.getFahrenheit();

Question 5

Consider the following class:

public class Book {
    private String title;
    private int pages;
    
    public Book(String t, int p) {
        title = t;
        pages = p;
    }
    
    public String getTitle() {
        return title;
    }
    
    public int getPages() {
        return pages;
    }
    
    public void addPages(int additional) {
        pages += additional;
    }
}

Assume that the following code segment appears in a class other than Book:

Book novel = new Book("Java Basics", 200);
novel.addPages(50);
/* missing code */

Which of the following can replace /* missing code */ so that the value 250 is printed?

A) System.out.println(pages);

B) System.out.println(novel.pages);

C) System.out.println(Book.getPages());

D) System.out.println(novel.getPages());

E) System.out.println(getPages());

// Answers to the questions:
// BCBDD

Homework: Assignment Overview

Due: 10/16/2025
Points: 1

In this assignment, you’ll demonstrate your understanding of instance methods by creating a Student class that tracks grades and calculates statistics. You’ll practice creating student objects, adding grades, calculating averages, and generating grade reports—all using instance methods that operate on each student’s individual data.

Requirements

Your program must include:

  • A Student class with at least 3 instance variables (name, total points, number of assignments)
  • A constructor that initializes the student’s name and sets initial values
  • At least 2 void instance methods that modify the student’s grades (addGrade, printReport)
  • At least 2 non-void instance methods that return calculated values (getAverage, getLetterGrade)
  • A main method that creates at least 2 Student instances and demonstrates all methods working independently

Homework Hack: Student Grade Tracker

Create a Student class that manages a student’s grades throughout a semester.

Required Instance Variables:

  • String name - the student’s name
  • int totalPoints - sum of all grade points earned
  • int numAssignments - count of assignments completed

Required Instance Methods:

  • addGrade(int points) - void method that adds a grade and updates totals
  • getAverage() - returns the student’s current average as a double
  • getLetterGrade() - returns a String letter grade (A, B, C, D, F) based on average
  • printReport() - void method that displays a formatted report of the student’s performance

Grading Scale:

  • A: 90-100
  • B: 80-89
  • C: 70-79
  • D: 60-69
  • F: below 60

Sample Output

Here’s an example of what your output should look like:

=== Student Grade Tracker System ===

Creating student: Emma Rodriguez
Student created successfully!

--- Adding Grades for Emma ---
Adding grade: 95 points
Adding grade: 88 points
Adding grade: 92 points
Adding grade: 85 points

--- Emma's Grade Report ---
Student Name: Emma Rodriguez
Total Points: 360
Assignments Completed: 4
Current Average: 90.0
Letter Grade: A
Status: Excellent work!

========================================

Creating student: James Wilson
Student created successfully!

--- Adding Grades for James ---
Adding grade: 78 points
Adding grade: 82 points
Adding grade: 75 points

--- James's Grade Report ---
Student Name: James Wilson
Total Points: 235
Assignments Completed: 3
Current Average: 78.33
Letter Grade: C
Status: Keep working hard!

========================================

Final Summary:
Emma Rodriguez - Average: 90.0 (A)
James Wilson - Average: 78.33 (C)

Submission Instructions

Create a section on your personal blog documenting your completed Student Grade Tracker. Insert the rubric provided below and self-grade yourself with comments as to why you think you deserved that grade. Add screenshots/proof of your code as proof that you fulfilled all the rubric requirements in your blog along with a screenshot of the output (similar to the one provided above).

After updating your blog, please submit a personal blog link of your completed assignment to the google form link inserted in the ‘CSA Sign Up Sheet - Team Teach - Trimester 1’ spreadsheet.

Grading Rubric

Criteria Percent Weight Description
Functionality 40% Program runs without errors, creates multiple Student objects, correctly adds grades, calculates averages, and assigns letter grades
Method Implementation 30% Includes all required methods (addGrade, getAverage, getLetterGrade, printReport) that properly access/modify instance variables
Code Quality 20% Clean code with meaningful variable names, proper constructor, and helpful comments explaining method purposes
Output & Presentation 10% Clear, well-formatted output showing multiple students with different grades and formatted reports

Tips for Getting Started

  • Review the Counter example from the lesson notes—your Student class will work similarly
  • Start by creating the Student class with the three instance variables
  • Write your constructor to initialize the name and set totalPoints and numAssignments to 0
  • Implement addGrade() first—it should add to totalPoints and increment numAssignments
  • Test each method before moving to the next one
  • Remember: Test your hack multiple times and add updates in small increments in case you run into an error

Tips for Success

  1. Start simple - Get your constructor and addGrade() working first before tackling calculations
  2. Watch for division - When calculating average, make sure to cast to double: (double)totalPoints / numAssignments
  3. Test with multiple students - Create at least 2 Student objects with different grades to show independence
  4. Comment your code - Explain what each method does, especially your letter grade logic

Bonus Challenges (Optional for Extra Credit)

Want to go above and beyond? Try adding:

  • A getHighestGrade() method that tracks and returns the best individual grade (you’ll need to store individual grades, not just the total)
  • A getLowestGrade() method for the lowest individual grade
  • A dropLowestGrade() method that removes the lowest grade from calculations
  • A compareTo(Student other) method that compares two students’ averages
  • Weighted grades—allow some assignments to be worth more points than others
  • A reset() method that clears all grades and starts fresh
  • Error checking to prevent negative grades or invalid input

Good luck!


import java.util.ArrayList;
import java.util.Collections;

public class StudentTrackerBonus {

    public static class Student implements Comparable<Student> {
        // Instance variables
        private String name;
        private ArrayList<Integer> grades;  // store individual grades

        // Constructor
        public Student(String name) {
            this.name = name;
            this.grades = new ArrayList<>();
            System.out.println("Creating student: " + this.name);
            System.out.println("Student created successfully!\n");
        }

        // --- Base Methods ---

        /** 
         * Adds a grade if it's valid (0–100).
         * Rejects negative or >100 grades with a warning.
         */
        public void addGrade(int points) {
            if (points < 0 || points > 100) {
                System.out.println("⚠️ Invalid grade (" + points + "). Must be 0–100.");
                return;
            }
            grades.add(points);
            System.out.println("Adding grade: " + points + " points");
        }

        /** 
         * Calculates the student's average grade.
         */
        public double getAverage() {
            if (grades.isEmpty()) return 0.0;
            int total = 0;
            for (int g : grades) total += g;
            return (double) total / grades.size();
        }

        /** 
         * Returns a letter grade based on the grading scale.
         */
        public String getLetterGrade() {
            double avg = getAverage();
            if (avg >= 90) return "A";
            if (avg >= 80) return "B";
            if (avg >= 70) return "C";
            if (avg >= 60) return "D";
            return "F";
        }

        /**
         * Prints a formatted grade report.
         */
        public void printReport() {
            System.out.println("\n--- " + this.name + "'s Grade Report ---");
            System.out.println("Grades: " + grades);
            System.out.printf("Average: %.2f%n", getAverage());
            System.out.println("Letter Grade: " + getLetterGrade());
            System.out.println("Highest Grade: " + getHighestGrade());
            System.out.println("Lowest Grade: " + getLowestGrade());
            System.out.println("Assignments Completed: " + grades.size());
            System.out.println("========================================");
        }

        // --- Bonus Features ---

        /** 
         * Returns the highest grade, or 0 if no grades exist.
         */
        public int getHighestGrade() {
            if (grades.isEmpty()) return 0;
            return Collections.max(grades);
        }

        /** 
         * Returns the lowest grade, or 0 if no grades exist.
         */
        public int getLowestGrade() {
            if (grades.isEmpty()) return 0;
            return Collections.min(grades);
        }

        /** 
         * Drops the lowest grade from the list.
         * Useful for grade forgiveness policies.
         */
        public void dropLowestGrade() {
            if (grades.isEmpty()) {
                System.out.println("No grades to drop.");
                return;
            }
            int lowest = getLowestGrade();
            grades.remove(Integer.valueOf(lowest));
            System.out.println("Dropped lowest grade: " + lowest);
        }

        /**
         * Compares this student's average to another student's.
         * Returns positive if this > other, negative if this < other, 0 if equal.
         */
        @Override
        public int compareTo(Student other) {
            return Double.compare(this.getAverage(), other.getAverage());
        }

        /**
         * Adds a grade with a weight factor (default weight = 1.0).
         * Weighted average will count this grade multiple times.
         */
        public void addWeightedGrade(int points, double weight) {
            if (points < 0 || points > 100 || weight <= 0) {
                System.out.println("⚠️ Invalid input for weighted grade.");
                return;
            }
            int times = (int) Math.round(weight);
            for (int i = 0; i < times; i++) {
                grades.add(points);
            }
            System.out.println("Added weighted grade: " + points + " (weight " + weight + ")");
        }

        /**
         * Resets all grades for this student.
         */
        public void reset() {
            grades.clear();
            System.out.println("All grades reset for " + name + ".");
        }
    }

    // === Main method ===
    public static void main(String[] args) {
        System.out.println("=== Student Grade Tracker BONUS SYSTEM ===\n");

        Student emma = new Student("Emma Rodriguez");
        emma.addGrade(95);
        emma.addGrade(88);
        emma.addGrade(92);
        emma.addGrade(85);
        emma.addWeightedGrade(100, 2.0); // bonus weighted grade
        emma.printReport();

        Student james = new Student("James Wilson");
        james.addGrade(78);
        james.addGrade(82);
        james.addGrade(75);
        james.printReport();

        System.out.println("\n--- Dropping Lowest Grade for James ---");
        james.dropLowestGrade();
        james.printReport();

        System.out.println("\n--- Comparing Students ---");
        int result = emma.compareTo(james);
        if (result > 0)
            System.out.println(emma.name + " has a higher average than " + james.name + ".");
        else if (result < 0)
            System.out.println(james.name + " has a higher average than " + emma.name + ".");
        else
            System.out.println("Both students have equal averages.");

        System.out.println("\n--- Resetting Emma’s Grades ---");
        emma.reset();
        emma.printReport();

        System.out.println("\n=== End of Bonus Tracker ===");
    }
}