Lab Assignment #5
Overview
- Login: login to the machine in CentOS (this is linux).CentOS/
- Part A: Use a simple if statement to replace one color with another.
- Part B: Explore if – else if – else with code a program to assign grades.
- Quiz: Each person will individually take a short quiz
Part A
- Right click on the Desktop and Select "Open a Terminal"
- Paste the following lines of code into the terminal
- The previous command should print out four filenames: Lab5A.java Lab5B.java Picture.java upperHalf_GreenToRed.txt
- Run Dr Java by double clicking on the white and blue icon that says “Dr Java” icon.
- In Dr. Java, open Picture.java
- Open the file upperHalf_GreenToRed.txt and copy the first method ONLY-- upperHalf_GreenToRed()-- and paste it at the end of Picture.java (right before the last closing curly brace)
- Now open Lab5A.java in Dr. java.
- As in Lab4 last week, replace the XX in the setMediaPath call with your account beginning with cs8wXX.
- Lab5A calls a method provided for us called explore(). The explore() method is very useful in that it pulls up a window where you can mouse over the picture and find the x,y coordinates of a point on the picture and the RGB components at that pixel. Save, compile, then run Lab5a.java
- What is the (approximate) range of green color components for the "“bird body"”? – (Move your mouse over parts of the bird body and see what the green component is.)
- You can use the explore() method to help you identify color values of interest in your pictures.
- What is going on?
- Given the method's name, upperHalf_GreenToRed, what do you think it's trying to do?
- The method upperHalf_GreenToRed() currently doesn’t change the green parts of the top half of the picture (the bird body) to red as the method name suggests.
- Instead, what does this method do? Examine the method upperHalf_GreenToRed()) method in Picture.java. Trace the value of the loop control variable i, and the boolean expression evaluated in the if statement expression for the first 6 iterations of the loop. Write down the value of i and ((i%2) == 0) for each of the first 6 iterations.
- How does the if statement expression line inside the loop create the effect that you noticed?
- How could you use the explore method on your redBird picture to check your theory?
- What code makes it so only the pixels from the top half of the picture are modified?
- Fix the code: Modify the if expression to change the color of the pixels in the top half of the picture to red if it previously had a green component greater than 180. Compile and test your code to see if it makes half a red bird (on top) and leaves the bottom half of the bird green.
- NOTE: Even if you have not completed part A and 20 minutes have passed, MOVE ON to part B. Otherwise continue with steps 12-18.
- Switch driver and navigator: if you've been controlling the mouse and keyboard, it's time for your partner to do so.
- Now you are going to write your own function that with the following header public Picture leftHalf_GreenToBlack(){}
- Copy the method header from line 12 into your Picture.java file. It is your job to fill in the body
- Like the previous method, this method will create a new copy of the calling Picture object, and then modify the pixels in the left half the picture with a green threshold value above 180 to be black.
- Hint: some of the code from the upperHalf_GreenToRed method may be reused for this method. Think about what's different and what's the same. Think about the different kinds of loops we've learned about, and which option may be best suited for this method (Nested Loops, While Loops, Do-While, For, Enhanced For).
- Once you have finished, uncomment out the bottom two lines in Lab5A.java to test your method. Recompile and run Lab5A.java.
- The final result should look as follows:
- cd ../public/Lab5
- make directories
- make install
- cd
- cd Lab5
- mv Lab5A.java.empty Lab5A.java
- mv Lab5B.java.empty Lab5B.java
- mv Picture.java.empty Picture.java
- ls
Part B
Switch driver and navigator: if you've been controlling the mouse and keyboard, it's time for your partner to do so.
- Open La5B.java in DrJava
- Read and Understand the Code
- Before you get started, read and understand the code for part B. It doesn’t do anything with Pictures – it just explores how the if statement expression structure in Java works.
- This code was developed to help assign grades in a course graded “"Pass/NoPass”. ". It reads in a “"score” " from the user (typed on the keyboard) and then prints one of two messages
- PREDICT: Before running the code, write down which message you expect the code print for the following three input scores. Score input: 0.71, 0.70, 0.69. Each answer will be either A or B.
- Compile, Run and Test:
- Compile the code, run it and test one of your inputs above (like 0.71). See if your predicted output is what is printed (look in the Interactions Pane to enter data and see printed messages).
- Why is the “"Please work harder next time” " message always printed out no matter what score is entered for the student? (If you don’t know, look on page 188 at the line "if (redValue < 60)" We control the “scope" of the if statement expression with { }.
- Assume we only want to print the "work harder" message for students who did NOT pass. Modify the code so that that the scope of the else statement expression controls both printing lines. (Ask for help if you need it).
- DO YOU UNDERSTAND? Why do we not need to have a condition like (x < .70) in the else statement expression?
- Compile the code, run it and test one of your inputs above (like 0.71). See if your predicted output is what is printed (look in the Interactions Pane to enter data and see printed messages).
- Consider the following situation:
- You are tasked with helping a professor automatically calculate final grades for students given an array of their scores
- For this professor's class, there are only 3 assignments and all of them are weighted equally. Assignment 1 is out of 20 points, Assignment 2 is out of 30 points, and Assignment 3 is out of 40 points.
- You decide to write a method called calculate_student_grade that takes in 2 parameters: the first is the students name and the second is the array of that student's scores. The first element in the array is the students score on assignment 1, the second is the score for assignment 2, and the third element is the score for assignment 3. The method will not return anything but will instead simply print out the students name and final letter grade.
- Uncomment the commented portion of the method and FILL IN the assignment of finalGrade so that it calculate the student's final grade and then prints out the students letter grade.
- Now test your method by uncommenting the second half of the main method in Lab5B.java. Recompile and run it!
- What letter grade does your imaginary student with perfect scores get? Is it what you expected? Is the letter grade for the average student what you expected?
- Let’s DEBUG by examining the execution of the method for our A student. The finalGrade variable should be 1.00, but the variable grade gets assigned a value four different times. When we type in 0.80 for the score, the variable grade gets assigned a value 3 three different times. Why is that happening?
- Fix the code: We only want the second “if” statement to evaluate execute when the first “if” statement DOES NOT evaluate to true. We only want the third “if” statement to evaluate execute when the first TWO “if” statements DO NOT evaluate to true (page 190 has an example of this). HINT: there is an additional conditional statement in java besides if and else. They only get executed as part of an else of the previous statement. So make the lines read like this:
else if (finalGrade >= .80)
else if (finalGrade >= .70)
else if (finalGrade >= .60) - Compile and test your code to make sure it prints the correct grade for each of the test cases
Can You Do?
- Revert your code back to using just if statement expressions. Change the boolean expressions controlling the if statements to be compound expressions that give the “correct” grades. HINT: You earn a B if your score is >= 80 and < 90.
- Which code is more efficient (executes fewer statement expressions) – the "if if - else if" version or the plain "if" versions?
Invite Your Partner for the Next PSA and Log Out
Click on System > Log Out cs8fzz... > Log Off
Complete Your Lab Quiz
See the instructor to get your individual lab quiz.
The quizzes are open book & note, but closed Dr Java and partner.
The quizzes are open book & note, but closed Dr Java and partner.
Sample Code
/*
* Lab5A: Changing the color of a bird
*/
public class Lab5A
{
public static void main( String[] args )
{
FileChooser.setMediaPath("/home/linux/ieng6/cs8f/REPLACE_ME/Desktop/mediasources/" );
Picture input1 = new Picture( "bird1.jpg" );
input1.explore();
Picture redBird = input1.upperHalf_GreenToRed();
redBird.show();
}
}
/*
* upperHalf_GreenToRed.txt
*/
public Picture upperHalf_GreenToRed()
{
Picture newPic = new Picture(this);
System.out.println("New picture width: " + newPic.getWidth());
System.out.println("New picture height: " + newPic.getHeight());
Color red = new Color(255,0,0);
Pixel[] pixelArray = this.getPixels();
Pixel[] newPicArray = newPic.getPixels();
for (int i = 0; i < newPicArray.length; i++)
{
if ((i%2) == 0)
{
newPicArray[i].setColor(red);
}
}
return newPic;
}
/*
* Lab 5B -- exploring if - else if - else with grade assignment
*/
import java.io.*;
public class Lab5B
{
public static void main (String[] args) throws IOException
{
// Get the student grade from the user
System.out.println("Please enter the student score as a percent (e.g. .89)");
/* The following two lines you don't have to understand,
but they read in a value from the keyboard of double type
(e.g. has a decimal point somewhere in it).
*/
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
double x = (new Double(br.readLine())).doubleValue();
// Calculate whether the student passed or failed and print a message
if (x >= .70)
System.out.println("Message A: Congratulations, you earned a pass");
else
System.out.println("Message B: I am sorry, you did not earn a passing grade");
System.out.println("Please work harder next time");
/*
char grade;
if ( x >= .90)
grade = 'A';
if (x >= .80)
grade = 'B';
if (x >= .70)
grade = 'C';
if (x >= .60)
grade = 'D';
else
grade = 'F';
System.out.println("The grade you earned was a " + grade);
*/
}
}
* Lab5A: Changing the color of a bird
*/
public class Lab5A
{
public static void main( String[] args )
{
FileChooser.setMediaPath("/home/linux/ieng6/cs8f/REPLACE_ME/Desktop/mediasources/" );
Picture input1 = new Picture( "bird1.jpg" );
input1.explore();
Picture redBird = input1.upperHalf_GreenToRed();
redBird.show();
}
}
/*
* upperHalf_GreenToRed.txt
*/
public Picture upperHalf_GreenToRed()
{
Picture newPic = new Picture(this);
System.out.println("New picture width: " + newPic.getWidth());
System.out.println("New picture height: " + newPic.getHeight());
Color red = new Color(255,0,0);
Pixel[] pixelArray = this.getPixels();
Pixel[] newPicArray = newPic.getPixels();
for (int i = 0; i < newPicArray.length; i++)
{
if ((i%2) == 0)
{
newPicArray[i].setColor(red);
}
}
return newPic;
}
/*
* Lab 5B -- exploring if - else if - else with grade assignment
*/
import java.io.*;
public class Lab5B
{
public static void main (String[] args) throws IOException
{
// Get the student grade from the user
System.out.println("Please enter the student score as a percent (e.g. .89)");
/* The following two lines you don't have to understand,
but they read in a value from the keyboard of double type
(e.g. has a decimal point somewhere in it).
*/
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
double x = (new Double(br.readLine())).doubleValue();
// Calculate whether the student passed or failed and print a message
if (x >= .70)
System.out.println("Message A: Congratulations, you earned a pass");
else
System.out.println("Message B: I am sorry, you did not earn a passing grade");
System.out.println("Please work harder next time");
/*
char grade;
if ( x >= .90)
grade = 'A';
if (x >= .80)
grade = 'B';
if (x >= .70)
grade = 'C';
if (x >= .60)
grade = 'D';
else
grade = 'F';
System.out.println("The grade you earned was a " + grade);
*/
}
}