EECS 2030 Summer 2023: Lab 1
(about 2 % of the final grade; may be done in groups of up to three students ) Introduction Students in the same lab section are allowed to work in groups of 2 or 3 students. Working alone is acceptable as well. The purpose of this lab is to review the following basic Java concepts that should have been covered in your previous courses: • style • using int and double values and variables • arithmetic and the methods provide d in java.lang.Math • Boolean expressions and bitwise operations • using objects • if statements • using String s • using List s • for loops This lab also introduces code testing using JUnit . This lab will be graded both for style and for correctness.
Style Rules for Coding The style rules ar e not overly restrictive in EECS2030.
- Your programs should use the normal Java conventions (class names begin with an uppercase letter, variable names begin with a lowercase letter, public static final constants should be in all caps, etc.).
- In general, use short but descriptive variable names. There are exceptions to this rule; for example, traditional loop variables are often called i, j, k, etc. Avoid very long names; they are hard to read, take up too much screen space, and are easy to mistype.
- Use a consistent indentation size. Beware of the TAB vs. SPACE problem: Tabs have no fixed size; one editor might interpret a tab to be 4 spaces and another might use 8 spaces. If you mix tabs and spaces, you will have indenting errors when your code i s viewed in different editors.
- Use a consistent brace style: // left aligned braces
class X { 2 public void someMethod() { // ... }
public void anotherMethod() { for (int i = 0; i < 1; i++) { // ... } } } or // ragged braces
class X { public void someMethod() { // ... }
public void anotherMethod() { for (int i = 0; i < 1; i++) { // ... } } }
- Insert a space around operators (except the period/dot "."). The following // some code somewhere boolean isBetween = (x > MIN_VALUE) && (x > MAX_VALUE); int someValue = x + y z; is much easier to read than this // AVOID DOING THIS // some code somewhere boolean isBetween=(x>MIN_VALUE)&&(x>MAX_VALUE); int someValue=x+yz; Note that in HTML the convention is the opposite (no spaces around attribute="value" )
- Avoid using "magic numbers". A magic number is a number that appears in a program in place of a named constant. For example, consider the following code: int n = 7 24; 3 What do the numbers 7 and 24 mean? Compare the code above to the following: final int DAYS_PER_WEEK = 7; final int HOURS_PER_DAY = 24; int n = DAYS_PER_WEEK HOURS_PER_DAY; In the second example, the meaning of 7 and 24 is now clear (better yet would be to also rename n). Not all numbers are magic numbers. You can usually use the val ues 0, 1, and 2 without creating a named constant. If you ever find yourself doing something like: final int TEN = 10; then you are probably better off using 10 and explaining its meaning in a comment.
- A good IDE (integrated development environment) s uch as Eclipse will correct many style errors for you. In eclipse, you can select the code that you want to format, right click to bring up a context menu, and choose Source -> Format to automatically format your code. You can also correct indentation only . The figure below illustrates typical styling violations.
Figure 1: Common code styling violations
Part 1: Getting Started Prerequisites : JDK and Eclipse If you are in the lab, you may skip to the next section. Developing Java applications requires a Java Development Kit (JDK). In this course we will also use Eclipse – an integrated development environment. These can be installed both separately or together1.
Java: Command -Line One way to compile and run Java code is to use a command line. For that, one writes the Java code using any plain -text editor (preferably an editor capable of at least highlighting the language’s syntax , such as Visual Studio Code, Atom, Notepad++ , then compiles and runs the applica tion that was compiled to byte -code s. Let’s assume the following content is saved to a file called HelloWorld.java :
In order to open the command line tool in the location where the file had been saved (and not have to use a cd command) , in Windows, one c an right -click on the directory containing the file while holding the Shift key:
Similar context -menu choices exist for other operating systems, e.g., in Linux (CentOS):
1 https://www.eclipse.org/downloads/packages/release/2023 -03/r/eclipse -ide-java-developers – or possibl y newer .
Then, the following commands compile and run the code (the full path is greyed o ut):
In case there are compilation or runtime errors, various error messages will be printed. Try introducing errors and see what kind of messages you receive.
6 Java: Eclipse Eclipse is an IDE (an Integrated Development Environment), meaning that it is a program made to provide you with all the tools you need to code, wrapped up in a nice user interface. Since most of you have already used other IDEs, such as Android Studio or Intelli J, you are going to find these familiar. Here are some of the main reasons for using an IDE:
Spot compiler errors quickly - if you've made some small mistake like forgetting a semicolon, or spelling a variable type wrong, the IDE will spot it quickly and let you know:
Autocomplete/Content Assist - this feature will save you time and effort by suggesting methods (and their parameters) and types. See below for an example:
Debug Mode - allows you to watch your variables and source code at any point in your program so you can find out exactly where your program is going wrong.
7 Built in console and compiler access - saves you the time from going back and forth from editor to console and vice versa.
8 A sample program in Eclipse:
- Start Eclipse The follo wing window appears (with some variations)
you will be asked to select a workspace. This is important! This is the root directory to which all of your programs will be saved to, so make sure you know where it is. One may click Browse... and create a dire ctory called eecs2030, workspace2030 –use any directory name that you like (including the default one workspace ); try to avoid spaces in the directory names.
- If the following window appears:
click on the orange Workbench button found near the top right corner.
-
create a Java Project. You can do this by doing: File -> New... -> Project... . The project wizard looks like this - click on Java Project .
-
Now, you will see a window like the one shown. Give your project a name, e.g., 'Tutorial'. You can name your project whatever you like, but avoid using spaces in the project name because this complicates navigating the directory structure of your project. Note that doing this now creates a directory in your previously created workspace directory. Keep the default settings and click finish.
-
If you see a popup window like the one showed here. Click Yes if that is the case. This will configure eclipse so th at it enables Java specific features.
-
create a package. To do this, right -click the new project you just created that will now appear in the Package Explorer on the left side, and then click New -> Package . Name it eecs2030 . Now if you look in the Packa ge Explorer, our eecs2030 package is under Tutorial -> src -> eecs2030 . src is the source folder. Hence, when it comes time to submit your files and you want to locate your source file, it will be in workspace -
Project ->src ->package ->file . So in our case, it would be: eecs2030/Tutorial/src/eecs2030/HelloWorld.java
-
create a HelloWorld.java. You can do this by right -clicking the package, then clicking New, and then Class . Enter the name of your class, in this case HelloWorld , and check the public static vo id main(String[] args) box - this will create the main method in your class for you. Our simple program does not inherit from any other program, so the other two boxes don ’t really matter.
-
Add System.out.print("Hello, world."); into the main body in the TODO section and then save your program by pressing Ctrl+s on your keyboard.
-
Now you can run your program by either clicking the green run button on the toolbar, or by right -clicking your package in the package explorer and selecting Run As... ->Java Application (find a keyboard shortcut for doing it quickly !). Note that the output appears in the console window at the bottom.
-
Submit that HelloWorld.java file via eClass and continue with Part 2 .
12 Part 2: Java Review Getting started These instructions assume that you have completed the previous parts of this lab, and have Eclipse running. In this lab, you will import an existing project rather than starting everything from scratch. In the eclipse File menu, choose the Import... menu i tem. In the Import dialog box that appears, choose the Existing Projects into Workspace item and click Next:
Use the included zip file. Click on the Select archive file radio button. Click on the Browse... button and select the file that you just downl oaded. Click the Finish button to import the project. Note that there is no need to unpack the zip file. On the left -hand side of the eclipse window, you will see a tab labelled Package Explorer . Use the small triangles to expand the lab1 contents, then th e src contents, and finally the eecs2030.lab1 contents. Double -click on Lab1.java and TestLab1.java to open these files in the editor:
Click on the Lab1.java tab. Lab1.java is the Java source code file that you need to edit to complete this lab. It contains several methods that you should be able to complete if you have mastered the material from your previous Java programming course or courses. Find the method with the hea der public static int m axInt() . Reading the Javadoc comment preceding the method, tells us that the method should return the smallest value that can be represented by the type int. Examining the body of the method in eclipse, we see that the method is impl emented like so: public static int m axInt() { return 0; } which is clearly incorrect. DON'T FIX THE METHOD YET; continue following the lab document. TestLab1.java is a test class that contains unit tests for all of the methods that you will implement in this lab. You will learn more about unit tests in your next lecture. For now, all you need to know is that you can use the test class to check for errors in the methods in Lab1.java . Click on the TestLab1.java tab in the editor window to view the cont ents of TestLab1.java . Run the test class by pressing the green run button indicated by the red arrow in the figure below:
The results of running the tests are shown to you in the JUnit tab located on the left -hand side of the eclipse window (see figure above). Notice that all of the tests have a blue x beside them; the blue x indicates that the test has failed. In the Failure Trace panel, some diagnostic information is shown to you. For the test01_m axInt test, the diagnostic information is indicating th at the test expected a value of 214748364 7 but received a value of 0. It seems like there is something wrong with our implementation of the maxInt method.
Click on the Lab1.java tab in the editor window to view the contents of Lab1.java . Scroll down to the maxInt method (the first method in the class). Edit the return value of the method so that it returns the correct value as shown below:
Save the edited file (use the File menu or type Ctrl-s). When you re -run the test class; you should see that the test test01_m axInt now has a green check mark beside it indicating that the test has passed. The remaining tests are still failing. In the remainder of this lab, you will use the te st class to help you fix the remaining methods in the Lab1 class. Follow the remainder of the lab to complete the exercises below. Most of the methods can be completed with a single line of code.
15 Primitive types In Java, all values have a type. A type defines a set of values and the operations that can be performed using those values. Java's primitive types are those types that are predefined by the Java language and are named by a reserved keyword. The primitive types are all numeric types and one type representing true/false values. int The int type represents integer values in the range −231 to (231 − 1). Java will interpret any number not having a decimal as being an int value. Constant values important to the int type can be found in the class java.lang.Integer . double The double type represents real values in the approximate range of −1.7 × 10308 to 1.7 × 10308. Java will interpret any number having a decimal point as being a double value. Exercise 1 Complete the method minPositiveDouble (). Refer to the method’s desc ription in the JavaDoc in -code comments. Run the JUnit tester after you complete each method to check your work. Exercise 2 Complete the methods removeLastThreeDigits(int n) and lastThreeDigits(int n) . Note that in removeLastThreeDigits (int n) and lastThreeDigits (int n) you do not need to create named constants for any magic numbers you might need. removeLastThreeDigits (int n) can be completed using integer division. lastThreeDigits (int n) can be completed using int eger remainder. You do not (and should not) need to use an if statement in either method. Run the JUnit tester after you complete each method to check your work. Exercise 3 Complete the method avg(int a, int b , int c). Be aware of the possibility of inco rrectly using integer division instead of floating -point division. 16 Run the JUnit tester after you complete each method to check your work. Exercise 4 Refer to the following link: https://en.wikipedia.org/wiki/Terminal_velocity for more detail. Complete the method terminalVelocity(double mass, double area, double c_d) using named constants to represent the constants in the formula. Use some reliable resour ce to find the constants . Exercise 5 Complete the methods isEven(int x) and isUnitVector(double x, double y) . Recall that the unit vector is a vector with a magnitude of 1 , so that x2 + y2 = 1. Run the JUnit tester after you complete each method to check your work. Exercise 6 Complete the method enrolStudent(int studentNumber) . Note that the method can throw a BadSIDException which is an exception class that has been included for you in the lab project. All the method should do is return true . However, the method should throw an exception if the number is not a 9 -digit number (at York there are other factors that would allow for checking the number validity; we use a simple hypothetical rule here). Run the JUnit tester after you complete each method to check your work. Exercise 7 Complete the method getCourseName() . To complete this method, you should first find the Lab1 class constant that contains the course name. You should then simply return the constan t to complete the method; in other words, you should not duplicate string containing the course name in your method. Run the JUnit tester after you complete each method to check your work. Exercise 8 Complete the method middleChar(String s) . See the code comments for the method to see the more formal definition of the middle character of a string. Run the JUnit tester after you complete each method to check your work. 17 Exercise 9 Complete the method alternatingCaps(String s) . The API for th e method defines what the method should return and contains several examples. To convert characters to lowercase, use the method Character.toLowerCase . To convert characters to uppercase, use the method Character.toUpperCase . The API for the Character class can be found here. Note that String class is immutable and using it would create many unnecessary objects , which will also cause your code to much sl ower than expected . Run the JUnit tester after you complete each method to check your work. Exercise 10 Complete the method secondByte (int n) . You will need to use bitwise operations here , such as &, |, <<, >>, or >>, and possibly casting into the required return type. You do not (and should not) need to use if statement s or loops in this method. Run the JUnit tester after you complete each method to check your work. If you have questions, don’t hesitate to post your questions on the course f orum on eClass , or contact the instructor directly (andriyp@eecs.yorku.ca ). Grading The assignment will be graded using the Common Grading Scheme for Undergraduate Faculties2. We look at whether the code passes the unit tests, and whether it conforms to the code style rules. Submission Find the Lab1.java file in your project and submit it electronically via eClass . Also submit the HelloWorld.java file from Part 1. If working in a group, make only one submission and include a group.txt file containing the names and the student numbers of the group members. The deadline is firm. Academic Honesty Direct c ollaboration (e.g., sharing your work results across groups ) is not allowed (plagiarism detection software may be employed). However, you’re allowed to discuss the assignment requirements, approaches you take, etc. Also, make sure to s tate any sources you use (online sources – including old solutions , books, etc.) . Although using outside sources may occasionally be allowed – with proper citing, if the amount of non -original work is excessive, your grade may be reduced.