956 views
owned this note
<style>
h3 {
border-bottom: 1px solid #ccc;
}
section {
margin-bottom: 2rem;
padding: 0em 1em;
padding-bottom: 1em;
border-radius: 4px;
background-color: #f7f7f7;
border: 1px solid #ccc;
}
summary {
font-weight: bolder;
}
summary:hover {
text-decoration: underline;
}
.todo {
color: #ff00ff;
border: 2px dashed #ff00ff;
padding: 0em 1em;
border-radius: 5px;
//display: none; // UNCOMMENT TO HIDE TODOs
}
</style>
# Homework 1A-from-FP (Spring 2025)
**Due: Tuesday, January 28 at 11:59pm EST**
:::info
**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 future assignments will assume you can handle these sorts of problems independently.
:::
**Need help?** Find us, as well as questions and answers from other students, on [EdStem](https://edstem.org/us/courses/69789/discussion). [Here’s our office hours schedule](https://brown-csci0200.github.io/calendars.html).
**Handin Instructions** are at the end of the document.
### 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/NDKzPaFm), accept the assignment and create a repository for your code. For step-by-step instructions on how to do this, see the **[Java Stencil setup guide](https://docs.cs200.io/s/java-stencil-setup-guide)**.
:::danger
**Important for Windows machines**: when you clone this repo, you might see red import statement regarding junit, something like `import org.junit.Assert` highlighted in red. First of all, check your top right corner: if you have the blue "Setup SDK" button, click it and select the Java version from the guide. If the error is still there, do the following:
- Hover over the red juint part, and follow the prompt that will say something like `add junit to path`.
- If `package sol` is still underlined in red, make sure that your top level directory (e.g. hw1-17a-username) is your root directory. To do this, right click on this folder inside IntelliJ, go to "Mark directory as", and make sure to mark it as "Sources Root" if the option is there.
- If `package sol` is still red, try right clicking on your `sol` folder, "Mark directory as", and select "Unmark as sources root"
- If your code still doesn't compile, post on Ed or come to hours!
:::
This assignment requires that you have IntelliJ installed and set up for this course. For details on the setup process, please see the [IntelliJ Setup Guide](https://docs.cs200.io/s/intellij-guide). If you’re having trouble, the guide includes a [Common Bugs/FAQ](https://docs.cs200.io/s/intellij-guide#Troubleshooting) section which might help.
:::info
<details><summary>Click here if you encounter errors about missing jar files when opening the stencil</summary>
If you receive errors about this, you may 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://docs.cs200.io/s/intellij-guide#Only-if-necessarynbsp-adding-JarsDependencies) section of the IntelliJ Setup Guide.
</details>
:::
Please make sure to read our [Gradescope submission guide](https://docs.cs200.io/gradescope-submission-guide) before handing in your assignment!
### Style Expectations
While you may have seen references to the course style guide, for this first assignment **we’ll only be expecting the following style requirements**:
- Method and variable names are in `camelCase`
- Class names are in `UpperCamelCase`
- Basic Javadocs for all methods and classes (look [here](https://docs.cs200.io/java-style-guide#Documentation-Comments) for examples)
### Relevant Documentation
Java is a large language with lots of optional code libraries. Going into the Java documentation for the kinds of questions arising in this homework will likely leave you more confused. 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
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: Super important notes :warning:
For this assignment, you will be creating several classes with fields. To be consistent with our autograder, you must follow a few conventions when doing this (for just this assignment):
- **Make all fields `public`**: When you declare fields in your classes, they should be `public`. That is, if you were creating a field called `length`, you should declare it as `public int length`, similar to what we did in class.
- **Naming**: Name your fields with **exactly** the same names as listed in this handout. Our autograder will try and access fields with these names--if you don't use them, there will be errors!
:::success
**What to expect in HW1**: The handout, and HW1 as a whole, guides you through developing the code in multiple 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.
:::
## Courses
Let’s start by creating a class representing a `Course`.
### Task 1-A
**Create a class named** `Course` in the `sol` directory of your stencil project.
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**.
To test this, write a JUnit test in the `Homework1ATest.java` file (more details about testing can be found in the [_Testing your work_](#Testing-your-work) and [_FAQ_](#FAQ) sections of this handout). This will confirm that you have everything set up properly.
:::info
**IntelliJ tip** / **if you see an error `cannot resolve symbol Course`**: When using a class in a file for the first time, you may need *import* the class Java can find it from your current file. To do this, you can ask IntelliJ to add an `import` statement to your current file, like this (as shown in the figure below):
1. Put your cursor over the name of the class showing the error (probably `Course`)
2. Click "Import Class" in the box that pops up

:::
<br>
### Task 1-B
Add a second constructor that takes only the department and course number as inputs, setting the credits to `1` (by default).
<details>
<summary>
<b>Why are we doing this? (click to show)</b>
</summary>
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.
</details>
<br>
### Task 1-C
**Add an error-checking mechanism to the original, three-argument constructor (ie, the one you made in Task 1-A).**
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.
throw new IllegalArgumentException("Invalid credits");
:::info
**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.
:::
<br>
### Task 1-D
**Write a method called** `toString` **in the** `Course` **class that takes no input and returns a** `String`**, combining the department and the course number.**
**Why?** 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).
:::info
<details>
<summary>
<b>Click for details</b>
</summary>
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"`.
// Sample output
"CSCI200"
You can concatenate, or combine, strings with the `+` operator. You can also concatenate a `String` and an `int` with the `+` operator to create a new `String` in Java.
Here’s a method stub for a generic `toString` method:
@Override
public String toString()
**You do not have to write Javadocs for this method.**
Why do we have to use an `@Override` tag?
</details>
:::
<br>
## Faculty and Students
Now let’s create some classes to represent `Faculty` and `Student`.
<br>
### Task 2-A
**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.
<br>
### Task 2-B
**Define a method** `isTeaching` **for faculty that takes a** `Course` **and returns a** `boolean `**indicating whether the faculty member is teaching that course.**
:::warning
**_Note:_** Use `==` to check for sameness for this and all other comparison questions for this assignment.
:::
<br>
### Task 2-C
**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.
<br>
### Task 2-D
**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.**
<br>
### Task 2-E
**Define a method** `totalCredits` **in** `Student` **that takes no inputs and returns the sum of the credits for the student’s two courses.**
<br>
### Task 2-F
**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.
<details>
<summary><b> Study Question </b></summary>
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!) </details>
## Testing your work
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! If you would like you can learn more about JUnit testing [here](https://docs.cs200.io/java-testing-guide).
<br>
### Task 3-A
**Write JUnit tests for the** `totalCredits` **method that is in the** `Student` **class.**
<br>
### Task 3-B
**Write JUnit tests for the** `canGrade` **method that is in the** `Faculty` **class.**
<br>
### Task 3-C
**Write JUnit tests to check that the** `Course` **constructor throws an exception if given an invalid number of credits.**
<br>
:::warning
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
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.
:::danger
**Important**: **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 `sol/` directory of your project.
:::
After completing this assignment, your `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`
- `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-17: Implementation** assignment on Gradescope:
- `Course.java` containing `public class Course`
- `Faculty.java` containing `public class Faculty`
- `Student.java` containing `public class Student`
You should **NOT** include the `AutograderCompatibility.java`, `TestRunner.java`, and `Homework1ATest.java` files from your submission.
Once you have handed in your homework, you should receive an email, more or less immediately, confirming your turn-in.
:::info
**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.
:::
:::warning
If Gradescope gives you the 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?**
:::info
<details>
<summary><b>Answer</b></summary>
<br>
A double is a data type that represents a decimal number. You can initialize a double similarly to an int, like so:
double myDouble = 0.4;
</details>
:::
### **How do I test** `Exceptions`**?**
:::info
<details>
<summary>
<b>Answer</b>
</summary>
<br>
The format for checking `Exceptions` is as follows:
```
@Test(expected = <exception-type>.class)
public void <test-name>() {
// code that results in exception
}
```
In practice, it looks something like this:
```
@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`.
</details>
:::
### **How do I test** `methods`**?**
:::info
<details>
<summary><b>Answer</b></summary>
<br>
The format for testing a `method` is as follows:
```
@Test
public void <test-name>() {
// code that tests the specific method
}
```
In practice, it looks something like this:
```
@Test
public void testOne() {
String name = this.professor.name;
assertEquals("Milda", name);
Course cs200 = new Course("CSCI", 200, 1.0);
assertEquals(1, cs200.credits, 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.
</details>
:::
***
_Please let us know if you find any mistakes, inconsistencies, or confusing language in this or any other CS200 document by filling out our_ [_anonymous feedback form_](https://forms.gle/Myj4XSPx8cBJLxGt5)_!_