---
tags: hw, spr22
---
# Homework 1A (CS 111/112/17/19): Classes and Methods
### Due: Tuesday, February 1st, 2022 at 11:59pm ET
**Collaboration Policy:** *You may collaborate as much as you want on this assignment* (this is more flexible than the normal course policy). The goal is to get everyone up to speed on Java. You are required to turn this in, but it will be weighted lightly in final grades. That said, we strongly encourage you to actively try writing these on your own while collaborating, as assignments after we come back together will assume you can do these sorts of problems on your own.
**Need help?** Find us, as well as questions and answers from other students, on [Ed](https://edstem.org/us/courses/16807/discussion/1054983). Here's our [office hours schedule](https://brown-csci0200.github.io/calendars.html).
**Handin Instructions** are at the end of the document.
<!---- :::warning
Don't bother with wheats and chaffs on this assignment. Let them just have a test class in the sol folder. There are enough other IDE logistics for them to sort out on this first assignment. General rule -- keep things focused and simple. This is a startup assignment only.
:::
:::warning
Beclear about what style requirements are expected (no access modifiers, basic javadoc on methods). They can ignore the rest of the style guide
::: --->
### Learning Objectives
- Practice writing classes, methods, and tests in Java
- Learn how to raise errors in Java
### Stencil Code and Assignment Setup
Using this [GitHub Classroom link](https://classroom.github.com/a/vGOTJ70G), accept the assignment and clone on your machine. See our [GitHub Guide](https://hackmd.io/jNFtrBaMQ0yx_AgKTPWyMg?view#Accepting-an-Assignment-on-GitHub-Classroom) for more detailed instructions.
Next, check out our [IntelliJ Setup Guide](https://hackmd.io/7azYQstzS4a6udptmaADCw) and make sure your IntelliJ has been downloaded and configured properly for this course. If you're having trouble, the guide includes a [Common Bugs/FAQ](https://hackmd.io/7azYQstzS4a6udptmaADCw#Common-BugsFAQ) section which might help.
In order to use JUnit (the framework you will be using to write tests in this class), you will need to add both the `hamcrest-core-1.3.jar` and `junit-4.13.2.jar` files as dependencies to your IntelliJ project. If you're not sure how to do this, check out the [Adding Jars/Dependencies](https://hackmd.io/7azYQstzS4a6udptmaADCw#Adding-JarsDependencies) section of the IntelliJ Setup Guide.
Please make sure to read our [gradescope submission guide](https://hackmd.io/oTbF1IUuRs27VgVJF4z2rA) before handing in your assignment!
### [Style Expectations](https://www.youtube.com/watch?v=b7k0a5hYnSI)
**Note:** Click on blue headers throughout for a fun surprise :)
While you may have seen references to the course style guide, for this first assignment **we'll only be expecting the following style requirements**:
* Basic Javadocs for all methods (you can look in the class notes for examples of these)
* Method and variable names are in `camelCase`
* Class names are in `UpperCamelCase`
For this assignment (1A), **you should not use access modifiers for fields** (private fields could break our autograder) If you don't know what they are yet, don't worry about it.
When creating fields make sure to **name them exactly** what is given in the handout. If you do not do this, the autograder will fail.
The handout guides you through developing the code in stages. **You will turn in one set of files with your cumulative work on all tasks.** You do *not* need to maintain versions of your code from each task separately.
### Relevant Documentation
Java is a large language with lots of optional code libraries and different ways of doing things. Honestly, we believe that going into the Java documentation for the kinds of questions arising in this homework will likely leave you more confused and less confident. The lecture materials should have everything you need. If not, ask us on Ed. We'll get to using the documentation on the next assignment.
------
## Problem Setup
It's the early 2000s! Brown wants to make a C@B-like website and you've been tasked to represent all the information about courses, faculty, and students. Each faculty member teaches one course. Students must take two courses each. Faculty are permitted to give grades to students taking the course that they are teaching.
<!---
:::warning
Things like these are general notes on homeworks. Should they be in a different document? They are making this assignment look longer than it is.
:::
<details>
<summary>Helpful notes on completing homeworks.</summary>
**Note:** The handout guides you through developing the code in stages. You will turn in one set of files with your cumulative work on all tasks. You do *not* need to maintain versions of your code from each task separately.
**Note:** You will see several study questions in the handout. You are **not** required to submit answers to these, but they are worth thinking through as a check on how well you understand the material conceptually (in addition to programming with it). We're happy to discuss the study questions on Ed, in office hours, etc.
</details>
-->
## Courses
Let's start by creating a class representing a `Course`.
**Task:** **Create a class named `Course`.**
- The class should have three fields:
- `department`, representing the department the course is being taught on (a `String` like `"CSCI"`),
- `courseNumber`, representing the course number of the course (an `int` like `200`),
- `credits`, representing the number of credits the course gives (a `double` that should be one of `0.5`, `1`, or `1.5`).
- The constructor of the class should take values for all three fields as inputs and set the field variables to these values.
At this point, make sure you are able to run your code and create an object from the `Course` class. You can do this by writing a JUnit test in the `Homework1ATest.java` file (more details about testing can be found in the *Testing your work* and *FAQ* sections of this handout). This will confirm that you have everything set up properly.
**Task:** **Add a second constructor that takes only the department and course number as inputs, setting the credits to `1` (by default).**
Since 1-credit courses are the default, we can reduce the chance of errors by allowing someone to omit the credits and having a constructor set the default value. In Java, a class can have multiple constructors, as long as their *signatures* are not the same. A constructor's signature is determined by the number and type of its parameters.
**Task:** **Add an error-checking mechanism to the three-argument constructor.**
The three-argument constructor allows someone to create an object with an invalid number of credits. Let's add some error checking to the constructor. Edit the body of the constructor to check whether the entered value is one of `0.5`, `1`, or `1.5`. If it is not, use the following statement to raise an error message. Errors in Java are called *exceptions* and throwing one will stop your program.
```=java
throw new IllegalArgumentException("Invalid credits");
```
**Note:** Java has different kinds of exceptions for different kinds of errors. For now, we will use an `IllegalArgumentException` when an input is not from an expected set of values.
<!---
`RuntimeException` for any error related to the logic of the program or system being represented.
-->
It helps for each object to have a string-based representation that we can use to print out the object in a readable form. In Java, every class has a default method named `toString` that shows how to display that class as a string (by returning a String—note the capital letter).
**Task:** **Write a method called `toString` in the `Course` class that takes no input and returns a `String`, combining the department and the course number.**
The string representation of a class should combine the department and the course number. For example, a course in department ``"CSCI"`` with number `200` should yield the string `"CSCI200"`.
```=Java
// Sample output
"CSCI200"
```
You can concatenate, or combine, strings with the `+` operator. You can also concatenate a `String` and a `int` with the `+` operator to create a new `String` in Java.
Here's a method stub for a generic `toString` method:
```=Java
@Override
public String toString()
```
**You do not have to write Javadocs for this method.**
::: spoiler Why do we have to use an `@Override` tag?
This is because a version of the `toString` method is automatically defined on all objects (you can try this by trying to print a `Course` object without defining a `toString` method). To fix this you should add the `@Override` annotation above the method definition to tell IntelliJ that you know you are changing this already defined method.
(To give a more technical explanation, this is because the default `toString` method is actually found in the `Object` class, which all classes in Java inherit. Therefore, in order to tell Java to use your `toString` instead, we use the `@Override` tag).
:::
<!--
**Note:** IntelliJ may complain trying to define the `toString` method. This is because a version of the `toString` method is automatically defined on all objects (you can try this by trying to print a `Course` object without defining a `toString` method). To fix this you should add the `@Override` annotation above the method definition to tell IntelliJ that you know you are changing this already defined method.
Experiment with creating valid and invalid `Course` objects, so you can get a feel for IntelliJ and how it works. -->
## [Faculty and Students](https://www.youtube.com/watch?v=5NPBIwQyPWE)
Now let's create some classes to represent `Faculty` and `Student`.
**Task:** **Create a class named `Faculty`.**
- The class should have three fields:
- `name`, representing the name of the faculty member (a `String` like `"Tall Kathi"`),
- `department`, representing the department that the faculty member teaches in (a `String` like `"CSCI"`),
- `teaching`, representing the course that they are currently teaching. For this assignment, we will assume that every faculty member is teaching exactly one course.
- The constructor of the class should take values for all three fields as inputs and set the field variables to these values.
**Task:** **Define a method `isTeaching` for faculty that takes a `Course` and returns a `boolean` indicating whether the faculty member is teaching that course.**
**Note:** Use `==` to check for sameness for this and all other comparison questions for this assignment.
**Task:** **Create a class named `Student`.**
- The class should have three fields:
- `name`, representing the name of the student (a `String` like `"Tall Aaron"`)
- `course1` and `course2`, representing the two courses that the student is taking (both of type `Course`). Assume that every student takes exactly two courses, and doesn't add or drop courses.
- The constructor of the class should take values for all three fields as inputs and set the field variables to these values.
- The constructor of `Student` should throw an `IllegalArgumentException` with the error message `"Invalid courses"` if the two courses are the same.
**Task:** **Define a method `isTaking` in `Student` that takes a `Course` and returns a `boolean` indicating whether this course is one of the two courses that the student is taking.**
**Task:** **Define a method `totalCredits` in `Student` that takes no inputs and returns the sum of the credits for the student's two courses.**
**Task:** **Add a method called `canGrade` to the `Faculty` class.**
Faculty can only grade students in their own courses. Add a method to the `Faculty` class called `canGrade` that takes a `Student` as input and returns a `boolean` indicating whether the faculty member is allowed to give a grade to that student.
**Study Question:** We could have represented courses within faculty and students as strings, such as `"CSCI0200"`. What's the advantage of using objects instead? Is there an advantage to using the strings? (No need to turn this in, but think about it!)
## [Testing your work](https://www.youtube.com/watch?v=Eo-KmOd3i7s)
We will be writing tests in JUnit, a testing framework for Java. The stencil code gives you a file `Homework1ATest.java` that includes the basic structure of a test. You'll test the methods and constructors that you wrote by adding to this file. See the FAQ section below for more in depth instructions on this!
**Task:** **Write JUnit tests for the `totalCredits` method in the `Student` class.**
**Task:** **Write JUnit tests for the `canGrade` method in the `Faculty` class.**
**Task:** **Write JUnit tests to check that the `Course` constructor throws an exception if given an invalid number of credits.**
For this assignment, you don't need to test any other methods. We're just trying to get you familiar with Java, JUnit, and how the pieces fit together.
-----
## How to Hand In <a name="handin"></a>
In order to hand in your solutions to these problems, they must be stored in appropriately-named files with the appropriate package header in an appropriately-named directory.
<!---
The source code files should comprise the `src` package, and your solution code files, the `sol` package. We mean that all your solution code should have a line at the top saying `package sol;` and they should be in the `hw01-classes/sol/` directory. For this assignment there is no `src` code, but in the future, it will have `package src;` and be in `<homework-name>/src/`.
-->
**Your solution code files should be in the `sol` package.** This means that all your solution code should have a line at the top saying `package sol;` and they should be in the `hw01-classes/sol/` directory.
After completing this assignment, your `hw01a-classes/sol/` directory should **contain** the following files:
* `AutograderCompatibility.java` containing `public class AutograderCompatibility`
* `Course.java` containing `public class Course`
* `Faculty.java` containing `public class Faculty`
* `Homework1ATest.java` containing `public class Homework1ATest`
* `Student.java` containing `public class Student`
* `TestRunner.java` containing `public class TestRunner`
To hand in your homework, **submit** the following files to the **Homework 1A: Implementation** assignment on Gradescope (make sure to exclude the `AutograderCompatibility.java` and `TestRunner.java` files from your submission):
* `Course.java` containing `public class Course`
* `Faculty.java` containing `public class Faculty`
* `Homework1ATest.java` containing `public class Homework1ATest`
* `Student.java` containing `public class Student`
Once you have handed in your homework, you should receive an email, more or less immediately, confirming your turn-in.
<!-- :::warning
TODO: Update AutograderCompatibility class
::: -->
<!---
You may have noticed a class `AutograderCompatibility`. Using this class is not required, but might help you debug if Gradescope tells you “The autograder failed to execute correctly". Please ensure that your submission is valid. Contact your course staff for help in debugging this issue. Make sure to include a link to this page so that they can help you most effectively. If Gradescope doesn't tell you "works with autograder", try uncommenting the main method of `AutograderCompatibility` and check that it compiles and runs.
There should be a class in the stencil code named`AutograderCompatibility`. Using this class is required to ensure that your submission is working correctly with the autograder. If Gradescope gives you message *“The autograder failed to execute correctly. Please ensure that your submission is valid. Contact your course staff for help in debugging this issue. Make sure to include a link to this page so that they can help you most effectively,"* uncomment the main method of `AutograderCompatibility` and check that it compiles and runs. Make a post on Ed or come to hours if it runs but still fails the Gradescope autograder.
-->
**Note on Autograder Compatibility:** There should be a class in the stencil code named `AutograderCompatibility`. Using this class is required to ensure that your submission is working correctly with the autograder. You will be penalized if your code does not work with the autograder.
If Gradescope gives you message *“The autograder failed to execute correctly. Please ensure that your submission is valid. Contact your course staff for help in debugging this issue. Make sure to include a link to this page so that they can help you most effectively,"* uncomment the main method of `AutograderCompatibility` and check that it compiles and runs. If the Gradescope autograder still doesn't work, come to hours or post on Ed for help.
## FAQ
**How do I use decimals in Java? What is a double?**
A double is a data type that represents a decimal number. You can initialize a double similarly to an int, like so:
```java
double myDouble = 0.4;
```
**How do I test `Exceptions`?**
The format for checking `Exceptions` is as follows:
```java=
@Test(expected = <exception-type>.class)
public void <test-name>() {
// code that results in exception
}
```
In practice, it looks something like this:
```java=
@Test(expected = IllegalArgumentException.class)
public void courseIllegalArgumentException() {
Course cs200 = new Course("CSCI", 200, 2.0);
}
```
Where creating a `Course` with `2.0` credits throws an `IllegalArgumentException`.
**How do I test `methods`?**
The format for testing a `method` is as follows:
```java=
@Test
public void <test-name>() {
// code that tests the specific method
}
```
In practice, it looks something like this:
```java=
@Test
public void testOne() {
String name = this.professor.name;
assertEquals(name, "Milda");
Course cs200 = new Course("CSCI", 200, 1.0);
assertEquals(cs200.credits, 1, 0.01);
}
```
Here we're first checking if `name` equals Milda. In the second example, we check to see if `credits` returned is within `0.01` of `1.0`. We need to include 0.01 as an argument in this case because `double` comparisons sometimes have slight imprecisions.
---
*Please let us know if you find any mistakes, inconsistencies, or confusing language in this or any other CS200 document by filling out the [anonymous feedback form](https://forms.gle/JipS5Y32eRUdZcSZ6)!*