CIS 425 Object Oriented Programming
Brightspace Course: CIS425Time and Place: 8:00 - 9:15 AM Tu/Th
Classroom: Tech Building 244
Office Hours: 7:30 - 7:55 AM Tu/Th 244 Tech (Virtual via MS Teams)
Email: (The best way to reach me)
US Mail Drop:
Buffalo State College
224 Technology Building
Buffalo, NY 14222
- Description
- Objectives
- Schedule
- Grading
- Textbook
- Assignments
- Exercises
- Communication
- Netiquette
- Policies
Description
Provide the student with exposure to an object-oriented approach to programming and design, including its history and rationale. Students gain hands-on programming experience using the Java object-oriented language to work through assignments with an increasing level of complexity.
The course will be conducted in a Hybrid format with an applied group-oriented undergraduate research approach.
Online course time will utilize our Brightspace course management website for access to reading material, assignments and projects. E-Mail and face-to-face group meetings will be utilized as a means to address assignment based discussion.
Prerequisites: CIS 251 or CIS 361, CIS 370.
Objectives
Upon successful completion of this course, students are expected to:
- understand the basics of using Java for Object Oriented Program (OOP) development.
- understand the Eclipse/JDK development environment for creating Java programs.
- comprehend the nature and complexities of Object Oriented Development (OOD).
- survey the Java platform (object libraries) and enterprise programming.
Lectures will consist of presentation of new material, demonstrations, reviews of assignments, and discussions of current readings and assignments. A substantial amount of outside work will be necessary to complete some of the assignments. Labs will consist of completing hands-on assignments.
The course may be conducted in a Hybrid format with an applied group-oriented undergraduate research approach. E-Mail, Brightspace and face-to-face in-class group meetings will be utilized as a means to address project based discussion.
Platform: Linux/Windows/MacOS X, JDK 1.7 or 1.8, or Notepad++/Textwrangler and Eclipse for Java. Students are responsible for installing software on their personal computers. Learning the operation of this software is the responsibility of the student. It helps if you can use your own desktop or laptop computer. The necessary software (JDK 8 and Eclipse) will be available in our classrooms and labs.
Schedule
Note: All assignments/exercises are due by 11:59 PM on the day they are listed as being due!
Each Chapter Test is only available for seven (7) days after the chapter is listed!
Chapter readings are from the Java Programming (Murach) textbook.
Module | Date | Textbook Reading | Chapter | Assignments/Tests | Assignments Due |
---|---|---|---|---|---|
Section 1 Get Started Right | |||||
1 | Aug 27 | Course Introduction, Administrivia An introduction to Java Programming |
1 | Brief Introduction Chapter 1 Test |
|
2 | Aug 29 | How to start writing Java code Using Eclipse |
2 | Brief Introduction Due | |
3 | Sep 3 | How to set up Windows/MacOS for this book | Appendix A/B |
Chapter 2 Test | |
4 | Sep 5 | How to use classes and methods | 3 | Chapter 3 Test Ex1 Average |
|
5 | Sep 10 | How to code your own classes and methods | 4 | Chapter 4 Test Assignment 1 Box |
|
6 | Sep 12 | How to structure an object-oriented application | 5 | Chapter 5 Test | Ex 1 Average Due |
7 | Sep 17 | How to Test and debug an application | 6 | Chapter 6 Test Ex 3 TaxWhiz |
|
Section 2 Essential skills as you need them | |||||
8 | Sep 19 | How to work with primitive types and operators | 7 | Chapter 7 Test | Ex 3 TaxWhiz Due |
9 | Sep 24 | How to code control statements | 8 | Chapter 8 Test | Assignment 1 Box Class Due |
10 | Sep 26 | How to work with strings | 9 | Chapter 9 Test Ex 7 Cube |
|
11 | Oct 1 | How to work with arrays | 10 | Chapter 10 Test | |
Section 3 Object-oriented programming skills | |||||
12 | Oct 3 | How to work with inheritance | 11 | Chapter 11 Test Ex 9 Box |
EX 7 Cube Due |
13 | Oct 8 | How to handle exceptions | 16 | Chapter 16 Test Ex 8 Donor Assignment 2 Course CIS425 |
|
14 | Oct 10 | How to work with file I/O | 17 | Chapter 17 Test Assignment 4 ReadWriteCSV |
Ex 8 Donor Due |
Oct 15 | Fall Recess - No Class | ||||
Section 4 More essential skills as you need them | |||||
15 | Oct 17 | How to develop a GUI with Swing (part 1) | 21 | Chapter 21 Test Ex 11 CyberStudent |
Ex 9 Box Due |
15 | Oct 22 | How to develop a GUI with Swing (part 1) | Lab | Ex 10 GradeCalc | Assignment 4 ReadWriteCSV Class Due |
16 | Oct 24 | How to develop a GUI with Swing (part 2) | 22 | Chapter 22 Test Ex 13 MeFirstPanel |
Assignment 2 CIS425 Class Due |
16 | Oct 29 | How to develop a GUI with Swing (part 2) | Lab | Ex 11 CyberStudent Due | |
Section 5 Real-world skills | |||||
17 | Oct 31 | How to work with a MySQL database | 19 | Chapter 19 Test Assignment 5 MySQL |
Ex 13 MeFirstPanel Due |
18 | Nov 5 | How to use JDBC to work with databases | 20 | Chapter 20 Test Ex 15 CDInterest |
Ex 10 GradeCalc Due |
18 | Nov 7 | How to use JDBC to work with databases | Lab | Assignment 3 Button | Ex 15 CDInterest Due |
19 | Nov 12 | How to work with dates and times | 15 | Chapter 15 Test Ex 16 Calculator |
Assignment 3 Button Class Due |
20 | Nov 14 | How to work with interfaces | 12 | Chapter 12 Test Ex 17 Pong |
Ex 16 Calculator Due |
21 | Nov 19 | TBA | Lab | Ex 18 Bounce | |
22 | Nov 21 | How to work with inner classes, enumerations, and documentation | 13 |
Chapter 13 Test |
Ex 17 Pong Due |
23 | Nov 26 | TBA | Lab | Ex 18 Bounce Due | |
Nov 28 | Thanksgiving Recess - No Class | ||||
24 | Dec 3 | TBA | Lab | Assignment 5 MySQL Class Due | |
25 | Dec 5 | TBA | Lab | Extra Credit Oracle Class Due | |
Dec 6 | Last Day of Classes | All Assignments and Exercises Due by Midnight! |
Chapters 14 How to work with collections, generics, and lambdas, and 18 How to work with threads are advanced topics and will only be briefly covered in class.
Grading
Students will be graded on:
- A Brief Introduction worth three (3) points.
- Nineteen (19) exercises worth three (3) points each.
- Four (4) assignments worth ten (10) points each.
- One Extra Credit assignment worth five (5) points.
- In-class and Discussion Forums participation, 0-5 points extra credit
Final grades will be based on total points
(105 available).
The final letter grades be based on the following table:
Grade | Range | Grade | Range | |||||
---|---|---|---|---|---|---|---|---|
A | 100 | - | 95 | C+ | 79 | - | 77 | |
A- | 94 | - | 90 | C | 76 | - | 74 | |
B+ | 89 | - | 87 | C- | 73 | - | 70 | |
B | 86 | - | 84 | D | 69 | - | 60 | |
B- | 83 | - | 80 | F | 59 | - | 0 |
Textbook
Any textbook that covers Java SE 8, Eclipse, Swing, and JDBC (MySQL) is acceptable.
You may also want to checkout my Guide To Object Oriented Programming With Java website.
Java Programming with Eclipse
Author: Joel Murach
Published August 2015
ISBN 978-1-890774-89-9
Publisher: Murach
You can download the data files (Free Downloads) and errata (Corrections) from this site. The files are also available from my Java with Eclipse website.
The code is also available in my Java Programming with Eclipse website.
Book is recommended!
Assignments
Introduction | Box | Course | Button | File I/O | Database
Brief Introduction (1 Point)
For this assignment you will login to your Blackboard Learn account and post a brief (75-100 words) introduction about yourself to the Brief Introduction Discussion forum for this course. Use the Add New Thread button and make the Subject line your name. Also, include any relevant course(s) you've taken that might help you in this course. This will give me a better idea of where each of us are in our understanding and experience with electronic commerce concepts and design. Please include a photo of yourself so we can get to know each other.
Create a Box Class (10 Points)
For this assignment you will create a Java class named Box that models a heavy "Box" with the following characteristics:
- The class has four private integer instance variables L1, W1, H1, Weight to store the Length, Width, Height, and Weight of the Box. Measurements are in feet and pounds.
- This class has two constructors:
- Constructor #1 - has no parameters and initializes the Box's instance variables to 0
- Constructor #2 - has four integer parameters that initializes the Box object's L,W,H,Weight
- This class has a method calculateVolume( ) which returns the volume (formula: L1*W1*H1) of the Box object as an integer
- This class has a method calculateDensity( ) which returns the density of the Box (formula: weight/volume) as a double, check for divide by 0.
- This class contains a main( ) method which creates an instance of the Box object with L1=10, W1=5, H1=5, Weight=2600 and computes the Box's Volume and Density, then outputs the results to the user's screen.
When you have this Assignment ready for me to view and grade you should upload your .java
file in
the Discussion Folder for this assignment.
Create a CIS425 Class (10 Points)
For this assignment you will create a Java class named CIS425
. This program can be
used to manage this CIS 425 course. Your task is to extend the base Student
class definition (below)
and customize it for CIS 425 students. Next, you will create a new class definition which will manage all CIS 425
students in this course. So, your program will have the following classes:
Student
(already written for you as a base class)CIS425_Student
(extends Student, you will have to write this)CIS425_Course
(manages all CIS425_Student objects, you will have to write this)
Here are the methods needed for CIS425_Student:
- Constructor:
public CIS425_Student( String name, int num_exams )
- Create an
int array exams[num_exams]
which will hold all exam grades for a student - Save
num_exams
for later error checking public boolean addGrade( int exam, int grade )
- Save a grade in the exams[ ] array at index exam
- If exam is out of range, return false (Note: exams are numbered 1,2,3,....)
- If OK, save the grade in
exams[ ]
array andreturn true
public int getGrade( int exam )
- Return grade saved in
exams[ ]
array at index exam - If
exam
is out of range,return -1
- If OK,
return grade
fromexams[ ]
array public String getName( )
- Return student name
Here are the methods needed for CIS425_Course:
- Constructor, create a class of
(int capacity)
CIS425_Students - Use an array: roster[ ] of size capacity to hold the CIS425_Student objects
- Also, save the capacity as a class variable and set an enrolled class variable to 0
public boolean addStudent( String name, int num_exams )
- Creates a new
CIS425_Student( name, num_exams )
object and add to theroster[ ]
array - Check to see if there is space for the new student, if no room, return false
- Create a new
CIS425_Student
object and add to theroster[ ]
array,return true
public CIS425_Student findStudent( String name )
- Find student with name and return object
- If student cannot be found, return null
public double computeAverage( int exam )
- Compute and return the course average on a specific exam ( that is, 1, 2, …) for all the students
- Check for divide by 0 and other errors
main( )
- Create a
CIS425_Course
of 30 students - Add two (2) students: Sally Smarty and Phil Phailure, each with 3 exams
- Search for these two students and give them a grade of 100 and 60 respectively on exam 1
- Output the average of the class on exam 1
Here is an outline of your program:
package edu.buffalostate.cis425.sp24.put-your-username-here;
public class CIS425_Student {
public CIS425_Student( String name, int num_exams ) { }
public boolean addGrade( int exam, int grade ) { }
public int getGrade( int exam ) { }
public String getName() { }
}
public class CIS425_Course {
public CIS425_Course( int capacity ) { }
public boolean addStudent( String name, int num_exams ) { }
public CIS425_Student findStudent( String name ) { }
public double computeAverage( int exam ) { }
public static void main( String[] args ) { }
}
---- class Student (this is given to you, so you do not need to copy it to your solution) -----
public class Student { private String sname; // Constructor, set name of student public Student( String name ) { sname=name; } // return name of student public String getName() { return sname; } }
When you have this Assignment ready for me to view and grade you should upload your .java
file in
the Discussion Folder for this assignment.
Create a Button GUI Program (10 Points)
For this assignment you will create a Java program that display a GUI program with buttons similar to this:
This GUI is the start of a simple number entry GUI class. The program displays four Buttons and every time the
user clicks on a button, the corresponding button label appears on the bottom of the GUI. As a hint, you might break
up the design of the GUI into two parts: one part holds the buttons, the other holds the completed GUI. Also include
a main ( )
to launch the GUI.
package edu.buffalostate.cis425.sp24.put-your-username-here;
public class SimpleButtons implements ...... {
SimpleButtons( ) { } //constructor
// event handler here
public static void main( String args[ ] ) { } // main here
}
When you have this Assignment ready for me to view and grade you should upload your .java
file in
the Discussion Folder for this assignment.
Create a Java Program That Reads and Writes a Text File (15 Points)
For this Assignment you will use Java to:
- Create a Class that manipulates the text file cis425_io.txt which can be downloaded from the Course Documents area of our Blackboard course and writes the cis425_ior.txt.
- Uses a Java
for
loop to walk through the file and generate a table with columns for the Month Number, Month Name, and Number of Days for each month.
-------------------------- | No | Month Name | Days | -------------------------- | 1 | January | 31 | | 2 | February | 28 | | 3 | March | 31 | | 4 | April | 30 | | 5 | May | 31 | | 6 | June | 30 | | 7 | July | 31 | | 8 | August | 31 | | 9 | September | 30 | | 10 | October | 31 | | 11 | November | 30 | | 12 | December | 31 | --------------------------
- Use appropriate Java comments throughout your code.
When you have this Assignment ready for me to view and grade you should upload a note in the PHP Input/Output Page
Discussion Folder with the URL of your home web page so I can click on that link and open your Assignment in a new browser window
(target="_new").
Back to Assignments
Exercises
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19
Exercise 1 - Average (3 Points)
package edu.buffalostate.cis425.sp24.put-your-username-here;
/*
* File: Average.java
*
* Write a program that inputs 10 integers from the keyboard and
* computes their average.
* if the user enters 9999, the program exits early, and outputs
* the average of the numbers entered so far.
*/
// Fill in the blanks to make the program work
import java.util.Scanner;
public class Average {
public static void main( String args[] ) {
int ave=0, cnt, num;
Scanner sc = new _____________;
System.out.println( "Integer Averaging Program" );
System.out.println( "Enter 10 Integers" );
cnt=0;
for ( ______________ ) {
System.out.print("Enter Integer "+i+": ");
num=sc.nextInt();
if (num==9999)
__________
cnt++;
ave=ave+num;
}
if ( )
ave= _____________;
else
____________
System.out.println("The average of " + cnt + " numbers is " + ave );
}
}
When you have this exercise ready for me to view and grade you should upload
your .java
file in the exercise Folder.
Exercise 2 - Temperature (3 Points)
For this exercise:
package edu.buffalostate.cis425.sp24.put-your-username-here;
/*
* File: Temperature.java
*
* Assignment: 1) Add two new methods:
* incrementTemp()
* decrementTemp()
* that increment and decrement the current temperature value
* by one degree respectively
* 2) Add a method: changeTemp( double t ) that adds t to the
* current temperature
* 3) Add a main() method to this class
* 4) In the main method: create two instances of the Temperature
* object each with a different
* temperature
* 5) Call the getTemp() method in each of the temperature objects
* and print the result to the users screen
* 6) Call the incrementTemp(), decrementTemp() and changeTemp(t)
* methods several times from the main() (use getTemp() to see
* if the temperature did change)
* Remember that there should not be any print statements in the
* Temperature class
*
* Description: This class stores the current temperature.
* It contains access methods to set and get the temperature.
*
*/
public class Temperature
{
private double currentTemp;
/**
* setTemp() sets the temperature to the given value
* @param t -- the given value
*/
public void setTemp(double t)
{
currentTemp = t;
}
/**
* getTemp() returns the current temperature
*/
public double getTemp()
{
return currentTemp;
}
/**
* incrementTemp() returns the (new) current temperature
*/
/**
* decrementTemp() returns the (new) current temperature
*/
/**
* changeTemp( double t ) adds t to current temperature and
* then returns the (new) temperature
*/
} // Temperature
When you have this exercise ready for me to view and grade you should upload
your .java
file in the exercise Folder.
Exercise 3 - TaxWhiz (3 Points)
package edu.buffalostate.cis425.sp24.put-your-username-here;
/*
* File: TaxWhiz.java
*
* Description: This class stores a tax rate and
* computes the tax for a given purchase price.
*
* Assignment: 1) Add a method changeTax() that changes the current tax
* rate by the amount in the parameter
* 2) Add a main method
* 3) In the main, create two instances of TaxWhiz with a tax
* rates of 8.75 and 4.75 percent
* 4) Compute the tax on two different purchases (one at the
* 8.75 and one at the 4.75 rates
* 5) Print the total of two purchases, the total tax and the
* total amount (purchases+tax)
* (try to make it look like a store receipt as best as you
* can, this actually could take trial/error)
* 6) Repeat steps 4) and 5) but first increment the tax rate
* by 1.0 percentage point
*/
public class TaxWhiz
{
private double taxRate;
/**
* TaxWhiz() constructor creates an object with
* a given tax rate
* @param t -- the given tax rate
*/
public TaxWhiz(double t)
{
taxRate = t;
}
/**
* calcTax() returns the tax for a given purchase
* @param purchase -- the given purchase price
*/
public double calcTax(double purchase)
{
return taxRate * purchase;
}
/**
* changeTax() changes the current tax
* @param t -- the change added to the current tax rate
*/
public void changeTax(double t)
{
// fill in code
}
} // TaxWhiz
When you have this exercise ready for me to view and grade you should upload
your .java
file in the exercise Folder.
Exercise 4 - NumberAdder (3 Points)
package edu.buffalostate.cis425.sp24.put-your-username-here;
/*
* File: NumberAdder.java
*
* Description: This class adds its two instance variables
* when the getSum() method is called.
*
* Assignment: 1) Add a getDifference method (to subtract num1-num2)
* 2) Add a getMult method to multiply the numbers
* 3) Add a getDiv method to divide the numbers num1/num2
* - check if num2 is not equal to 0.0 before division
* - if num2 is 0.0 return the value: Double.NaN
* 4) Test the new methods in the main()
*/
public class NumberAdder
{
private double num1;
private double num2;
/**
* setNums() sets the two instance variables from the given parameters
* @param n1 -- one of the given numbers
* @param n2 -- the second given number
*/
public void setNums(double n1, double n2)
{
num1 = n1;
num2 = n2;
} // setNums()
/**
* getSum() returns the sum of the two instance variables
*/
public double getSum()
{
return num1 + num2 ;
} // getSum()
/**
* main() creates two instances of this class and tests its
* setNums() and getSum() methods
*/
public static void main(String args[])
{
NumberAdder adder1 = new NumberAdder(); // Create two instances
NumberAdder adder2 = new NumberAdder();
adder1.setNums(10,15); // Set the instances' values
adder2.setNums(100,200);
System.out.println("Sum of adder1 " + adder1.getSum()); // Print the values
System.out.println("Sum of adder2 " + adder2.getSum());
} // main()
} // NumberAdder
When you have this exercise ready for me to view and grade you should upload
your .java
file in the exercise Folder.
Exercise 5 - NumberCruncher (3 Points)
package edu.buffalostate.cis425.sp24.put-your-username-here;
/*
* File: NumberCruncher.java
*
* Description: This class stores a number and contains
* methods to calculate the number's double, triple, and so on.
*
* Assignment: 1) add a new method cubeNumber() that returns the number^3
* power (num*num*num)
* 2) add a new method sixthNumber() that returns the number^6
* power, but it can use only one multiplication in the
* method (can't use num*num*num*num*num*num). Hint use the
* other methods that are available - and do not use the
* Math.pow() function
* 3) Test cubeNumber() and sixthNumber() in the main method
*/
public class NumberCruncher
{
private double num; // The instance variable
/**
* NumberCruncher() constructor creates an instance that
* stores the number given as its parameter
* @param number -- the number that will be stored
*/
public NumberCruncher(double number)
{
num = number;
}
/**
* getNum() returns the object's number
*/
public double getNum()
{
return num;
}
/**
* doubleNum() returns the object's number times 2
*/
public double doubleNum()
{
return num * 2;
}
/**
* tripleNum() returns the object's number times 3
*/
public double tripleNum()
{
return num * 3;
}
/**
* squareNum() returns the square of the object's number
*/
public double squareNum()
{
return num * num;
}
/**
* main() creates an instance of this class and tests its
various methods
*/
public static void main( String args[] )
{
NumberCruncher cruncher1 = new NumberCruncher(10);
System.out.println("Value of num is " + cruncher1.getNum());
System.out.println("num doubled is " + cruncher1.doubleNum());
System.out.println("num tripled is " + cruncher1.tripleNum());
System.out.println("num squared is " + cruncher1.squareNum());
} // main()
} // NumberCruncher
When you have this exercise ready for me to view and grade you should upload
your .java
file in the exercise Folder.
Exercise 6 - Triangle (3 Points)
package edu.buffalostate.cis425.sp24.put-your-username-here;
/*
*
* File: Triangle.java
*
* Create a Java class named Triangle that represents a "triangle"
* with the following characteristics:
*
* 1) The class has three private integer instance variables
* (S1, S2, S3) to store the sides of the triangle.
* 2) This class has two constructors:
* Constructor #1 - has no parameters and initializes the
* triangle's sides to 0
* Constructor #2 - has three integer parameters that
* initializes the triangle's sides
* 3) This class has a method calculatePerimeter( ) which
* returns the perimeter (s1+s2+s3) of the triangle as an
* integer
* 4) This class contains a main( ) method which creates an
* instance of the triangle object with
* S1=10, S2=5, S3=2 and computes the object's perimeter
* (via calculatePerimeter) and outputs the result to the
* user's screen.
*
*/
public class Triangle {
private int ___________________;
public Triangle ( ) {
}
public Triangle ( int s1, int s2, int s3 ) {
}
public int calculatePerimeter( ) {
}
public static void main( String args[] ) {
Triangle t = new __________________
System.out.println("The perimeter of t is: " + t.calculatePerimeter() );
}
}
When you have this exercise ready for me to view and grade you should upload
your .java
file in the exercise Folder.
Exercise 7 - Cube (3 Points)
package edu.buffalostate.cis425.sp24.put-your-username-here;
/*
* File: CubeUser.java
*
* Description: This class creates an instance of the Cube
* class and prints its area and volume.
*
* Assignment: 1) Create 3 cube objects. The size of each of the cubes
* should be input from the keyboard
* (hint: study the code below)
* 2) Print the Side length, Surface area and Volume to the
* users screen for each of the cubes
* 3) The program should catch input error exceptions and
* deal with them in a reasonable manner
*
*/
import java.util.Scanner;
public class CubeUser
{
/**
* main() -- creates an instance of Cube and tests it
*/
public static void main(String args[]) throws IOException
{
int length;
// HINT: input the side from the keyboard and check for errors and exceptions
Cube cube1 = new Cube(10);
System.out.println("Side length of cube1 is " + cube1.getLength());
System.out.println("Surface Area of cube1 is " + cube1.calculateSurfaceArea ());
System.out.println("Volume of cube1 is " + cube1.calculateVolume());
} // main()
} // CubeUser
When you have this exercise ready for me to view and grade you should upload
your .java
file in the exercise Folder.
Exercise 8 - Donor (3 Points)
package edu.buffalostate.cis425.sp24.put-your-username-here;
/*
* File: Donor.java
*
* Description: This class represents a donor to an
* organization. It stores the donor's name and rating.
* The main() method tests the class's methods.
*
* Assignment: 1) Add a new level "low" to this class (in addition to
* "high", "medium", "none")
* 2) Add a new method:
* public void updateRating(double amt){ } which
* recalculates a donor's rating according to the following
* schedule:
* a) amt = 0 - none
* b) amt < $100 - low level
* c) amt >= $100 and amt < $1000 - medium level
* d) amt >= $1000 - high level
* updateRating() should change the instance variable:
* rating to the new value
* 3) Modify this template to include an address variable and
* change the constructor to accept this new variable
* (along with the parameters). Basically, the object
* stores the donor's name, address and rating
* 4) Create a new donor (donor4) with an initial "low" rating,
* a) then let donor4 contribute $150,
* b) print this donor's new rating to the CRT
* 5) Modify the rest of the program (as needed) so that it compiles and runs correctly
*
*/
public class Donor
{
private String name = "no name";
private String rating = "none";
/**
* Donor() constructor sets the object's name and rating
* @param str -- a String giving the donor's name
* @param str2 -- a String giving the donor's rating
*/
public Donor(String str, String str2)
{
name = str;
rating = str2;
}
/**
* getName() returns the donor's name
* @return a String giving the person's name
*/
public String getName()
{
return name;
}
/**
* getRating() returns the donor's rating
* @return a String giving the person's rating
*/
public String getRating()
{
if (rating.equals ("high"))
return "high";
if (rating.equals ("medium"))
return "medium";
return "none";
}
/**
* main() creates three Donor instances and tests this
* classes methods.
*/
public static void main (String argv[])
{
Donor donor1 = new Donor("NewDonor", "high");
System.out.println("Donor's name is " + donor1.getName());
System.out.println(donor1.getName() + "'s rating is " + donor1.getRating());
Donor donor2 = new Donor("NewDonor2", "medium");
System.out.println("Donor's name is " + donor2.getName());
System.out.println(donor2.getName() + "'s rating is " + donor2.getRating());
Donor donor3 = new Donor("NewDonor3", "none");
System.out.println("Donor's name is " + donor3.getName());
System.out.println(donor3.getName() + "'s rating is " + donor3.getRating());
} // main()
} // Donor
When you have this exercise ready for me to view and grade you should upload
your .java
file in the exercise Folder.
Exercise 9 - Box (3 Points)
package edu.buffalostate.cis425.sp24.put-your-username-here; /* * File: Box.java * Author: Java, Java, Java * Description: This program draws a rectangular box of * asterisks given the number of rows and columns from * the user. */ /* * Assignment: 1) Add to the KeyboardReader class a new method: * public int getKeyboardIntegerRange(int min, int max) {} * that inputs a number from the keyboard, but limited to * a range: min, max. The function should not return * until the user cooperates and enters a number in the * correct range. Check for exceptions and handle errors * properly. * 2) Fix Box.java so that it compiles properly, there are * at least two possible fixes * 3) Test your new getKeyboardIntegerRange() method in * the Box (main) class to see if it works */ import java.io.*; public class Box { /** * drawBox() draws a row x col box of asterisks * @param row -- an int giving the number of rows * @param col -- an int giving the number of columns */ public void drawBox (int row, int col) { for (int k = 0; k < row; k++) { for (int j = 0;j < col; j++) System.out.print('*'); System.out.println(); } } // drawBox() /** * main() inputs the number of rows and columns from the * user and invokes the Box.drawBox() method to draw a box. */ public static void main(String args[]) throws IOException{ int nRows = 0; int nColumns = 0; KeyboardReader input = new KeyboardReader(); System.out.print("Enter the number of rows you want in your box: "); nRows = input.getKeyboardInteger(); System.out.print("Enter the number of colums you want in your box: "); nColumns = input.getKeyboardInteger(); System.out.println("This is what your box looks like\n"); Box.drawBox(nRows, nColumns); } // main() } // Box package edu.buffalostate.cis425.sp24.put-your-username-here; /* * File: KeyBoardReader.java * */ import java.io.*; // See Box.java for instructions public class KeyboardReader implements UserInterface { private BufferedReader reader; public KeyboardReader() { reader = new BufferedReader(new InputStreamReader(System.in)); } public String getKeyboardInput() { return readKeyboard(); } public int getKeyboardInteger() { return Integer.parseInt(readKeyboard()); } // HINT: add new method that limits input in range from Min to Max // public int getKeyboardInteger(int min, int max) {} // fill in rest, method should not return until the user entered number is within range // Prompt user with message if number is not within range before looping for another try. // Catch exceptions public double getKeyboardDouble() { return Double.parseDouble(readKeyboard()); } public String getUserInput() { return getKeyboardInput(); } public void prompt(String s) { System.out.print(s); } public void report(String s) { System.out.print(s); } public void display(String s) { System.out.print(s); } private String readKeyboard() { String line = ""; try { line = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return line; } } package edu.buffalostate.cis425.sp24.put-your-username-here; public interface UserInterface { public String getUserInput(); public void report(String s); public void prompt(String s); }
When you have this exercise ready for me to view and grade you should upload
your .java
file(s) in the exercise Folder.
Exercise 10 - GradeCalc (3 Points)
package edu.buffalostate.cis425.sp24.put-your-username-here; /* * File: GradeCalculator.java * Author: Java, Java, Java * Description: Instances of this class are used to calculate * a course average and a letter grade. In order to calculate * the average and the letter grade, a GradeCalculator must store * two essential pieces of data: the number of grades and the sum * of the grades. Therefore these are declared as instance variable. * Each time calcAverage(grade) is called, a new grade is added to * the running total, and the number of grades is incremented. */ /* * 1) Change the program so that it outputs +/- letter grades (you can decide * the thresholds ) * * 2) Output, in addition to the average and letter grade, the number of grades * entered so far. This requires a new method in the GradeCalculator class: * public int getCount() * * 3) Modify the addGrade() method in the GradeCalculator class so that it will * reject grades that are out of range... and do not update the grade count if * there is a problem with the grade range. * a) notify the user that the grade has been rejected, but keep the program * running * * 4) Check user input for errors. The program should handle the entry of characters, * and other non-numeric symbols without causing a crash */ public class GradeCalculator { private int gradeCount = 0; // GradeCalculator's internal state private double gradeTotal = 0.0; /** * calcAdd() is given a grade, which is added to * the running total. It then increments the grade count * . */ // Hint: change code to reject grades out of the range 0 to 100 by returning false, do // not update gradeCount if there is an error public boolean addGrade(double grade) { gradeTotal += grade; ++gradeCount; return true; } // calcAdd /** * calcAverage() is given a grade, which is added to * the running total. It then increments the grade count * and returns the running average. */ public double calcAvg() { return gradeTotal/gradeCount; } // calcAvg // HINT: // Add a new public method that returns the gradeCount // public int getCount() -- fill in rest of code /** * calcLetterGrade() returns the letter grade for this object. * Algorithm: The course average is first computed from the stored * gradeTotal and gradeCount and then converted into a * letter grade. * @return a String representing "A" through "F" */ public String calcLetterGrade () { // HINT: Change if/else logic for +/- letter grades double avg = gradeTotal / gradeCount; // Get the average if (avg >= 90.0) return "A"; else if (avg >= 80.0) return "B"; else if (avg >= 70.0) return "C"; else if (avg >= 60.0) return "D"; else if (avg >= 0) return "F"; return "Error"; } //calcLetterGrade() } // GradeCalculator package edu.buffalostate.cis425.sp24.put-your-username-here; /* * File: GradeCalcMain.java * Author: Java Java Java - * Description: This program creates a GradeCalcPanel and * adds it to the Frame's content pane and sets its size. */ // See GradeCalculator.java for instructions import javax.swing.*; public class GradeCalcMain extends JFrame { public GradeCalcMain() { getContentPane().add(new GradeCalcPanel()); //register 'Exit upon closing' as a default close operation setDefaultCloseOperation( EXIT_ON_CLOSE ); } // GradeCalcFrame() constructor public static void main(String args[]){ // change GUI so that it looks like Windows GUI, don't worry about this now try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (Exception e) {} GradeCalcMain aframe = new GradeCalcMain(); aframe.setSize(450,75); aframe.setVisible(true); } // main() } // GradeCalcMain class package edu.buffalostate.cis425.sp24.put-your-username-here; /* * File: GradeCalcPanel.java * Author: Java Java Java - * This class provides a user interface to * the GradeCalc class, which calculates a student's average * and letter grade for grades input into a JTextField. * The interface consists of input and output JTextFields and * and button to calculate the course average and letter grades. */ // See GradeCalculator.java for instructions import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.text.*; public class GradeCalcPanel extends JPanel implements ActionListener { private JLabel prompt; // GUI components private JTextField inputField; private JLabel resultLabel; private JTextField resultField; private JButton button; private GradeCalculator calculator; // The Calculator object public GradeCalcPanel() { calculator = new GradeCalculator(); // Create a calculator instance // setLayout( new GridLayout(1,5,10,10)); prompt = new JLabel("Grade:"); resultLabel = new JLabel("Average:"); inputField = new JTextField(10); resultField = new JTextField(20); resultField.setEditable(false); button = new JButton("Enter"); button.addActionListener(this); add(prompt); add(inputField); add(button); add(resultLabel); add(resultField); inputField.setText(""); } // GradeCalcPanel() /** * actionPerformed() handles clicks on the button. * It takes the data from the input JTextFields, and sends them to * the GradeCalculater class to calculate a running average and * computes the letter grade, which are displayed in TextFields. * @param e -- the ActionEvent the generated this system call */ public void actionPerformed(ActionEvent e) { double grade, ave; DecimalFormat df = new DecimalFormat("0.00"); String inputString = inputField.getText(); // HINT: use try/catch blocks to catch bad input to parseDouble() grade = Double.parseDouble(inputString); inputField.setText(""); // HINT: reject a bad grade in some way (the modified addGrade will return false // there is a problem with the grade calculator.addGrade(grade); // HINT: output grade count along with average and letter grade ave = calculator.calcAvg(); String average = "" + df.format(ave); String letterGrade = calculator.calcLetterGrade(); resultField.setText(average + " " + letterGrade); } // actionPeformed() } // GradeCalcPanel class
When you have this exercise ready for me to view and grade you should upload
your .java
file in the exercise Folder.
Exercise 11 - CyberStudent (3 Points)
For this exercise:
Create a CyberStudent class (similar to Cyberpet) with the following characteristics/properties:
- CyberStudent has 2 basic states and each of these basic states have several substates:
- a) awake
Substates:- eating
- working
- b) sleeping
Substates:- dreaming
- snoring
- A constructor that accepts a String object which is the name of the newly created CyberStudent, which is initially sleeping and dreaming
- CyberStudent has 2 basic methods that change the state of the CyberStudent to one of the 2 basic allowable states:
- boolean Awake( int Substate )
- boolean Sleep( int Substate )
Check the substate parameter ( int Substate ) in the above methods for consistency (within range) before changing the state (and substate). Return true if state was successfully changed, false otherwise. If there is a problem, return false without changing anything.
In addition, create mutator methods for each of the substates:
boolean Eat( ), Work( ), Dream( ), Snore( )
Each of these substate mutator methods should check for consistency, for example, a
Cyberstudent in the awake state cannot be placed in the substate snoring. Return
true if substate was changed, false otherwise.
CyberStudent has 2 accessor methods:
- getState( ): returns a String object giving the current state (and substate) of the CyberStudent
- getName( ): returns a String object giving the name of the CyberStudent object.
Notes: DO NOT USE Strings to store the "state" of the CyberStudent...
When you have this exercise ready for me to view and grade you should upload
your .java
file in the exercise Folder.
Exercise 12 - PairManager (3 Points)
For this exercise we are going to write a Pair Manager class that manages a pair of integers. This class will create and manage two integers. To simplify this problem, we will only define a few management methods (functions). A more useful class would have many more management methods. We want our class to be robust, so we will add error checking as appropriate.
Problem Statement
Create a PairManager class with the following characteristics/properties/methods:
- A default constructor that initializes the pair of integers to 0.
- There will be several public and private methods defined in this class:
- private int getInput(String prompt) - this method returns an integer from the keyboard. You must check for exceptions with try/catch blocks and recover gracefully from an exception. The prompt string is printed as a user prompt.
- public boolean getPair( ) - this method assigns values to the pair of integers by reading two numbers. You should call getInput( ) for each number.
- public int getFirst() - this method returns the first integer
- public int compAverage( ) - returns the average of the pairs.
- main ( ) - this method is the entry point to the program; it should create a PairManager object, call getPairs( ) and output the average of the pair.
When you have this exercise ready for me to view and grade you should upload
your .java
file in the exercise Folder.
Exercise 13 - MeFirstPanel (3 Points)
package edu.buffalostate.cis425.sp24.put-your-username-here; /* * File: MeFirstPanel.java * * Description: This class defines a GUI in a JPanel which contains * two JButton with initial labels "Me first!" and "Me next!". * Pressing either button causes the labels to be exchanged. * * Assignment: 1) Add a third button to the panel, with the label "third" * 2) Every time any of the buttons are pressed, the labels * should shift one place to the right first->second->third * would shift to third->first->second when one of the buttons * was pressed */ import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MeFirstPanel extends JPanel implements ActionListener { private JButton aButton; private JButton bButton; // add button here String aText = "first"; String bText = "second"; // add string here String tempText; // To use to exchange labels public MeFirstPanel() { aButton = new JButton(aText); aButton.addActionListener(this); // add event handler bButton = new JButton(bText); bButton.addActionListener(this); // add event handler add(aButton); // add button to JPanel add(bButton); // add button to JPanel } // MeFirstPanel() public void actionPerformed(ActionEvent e) { tempText = aText; // Exchange the strings aText = bText; bText = tempText; // add code here aButton.setText(aText); // Set button labels bButton.setText(bText); // add code here } // actionPeformed() } // MeFirstPanel class package edu.buffalostate.cis425.sp24.put-your-username-here; /* * File: MeFirstApp.java * * Description: This app creates a MeFirstPanel and * adds it to the app's content pane. * * Assignment: see MeFirstPanel.java * */ import javax.swing.*; public class MeFirstApp extends JFrame { public MeFirstApp() { setSize(200,200); getContentPane().add(new MeFirstPanel()); //register 'Exit upon closing' as a default close operation setDefaultCloseOperation( EXIT_ON_CLOSE ); } public static void main(String args[]) { MeFirstApp b = new MeFirstApp(); b.setVisible(true); } // main() } // MeFirstApp class
When you have this exercise ready for me to view and grade you should upload
your .java
file in the exercise Folder.
Exercise 14 - LeftRightPanel (3 Points)
package edu.buffalostate.cis425.sp24.put-your-username-here; /* * File: LeftRightPanel.java * * Description: This class defines a GUI in a JPanel which contains * two JButtons with initial labels "Left" and "Right" and a * JTextField. Pressing a button causes the label of that button * to be printed into the textfield. * * Assignment: 1) Create a centerButton (label it "Center") * 2) Create another JPanel * 3) Add the Left,Center,Right Buttons to the JPanel * in step 2 * 4) Change the Layout Manager of LeftRightPanel to * BorderLayout * 5) Place the JPanel of step 2 in the center position * of LeftRightPanel * 6) Place the JTextField( outField ) in the south * position of LeftRightPanel * 7) Change the ActionEvent code so the pressing the * centerButton displays "center' in the outField */ import javax.swing.*; import java.awt.*; import java.awt.event.*; public class LeftRightPanel extends JPanel implements ActionListener { private JButton leftButton; private JButton rightButton; // HINT: declare new JButton private JTextField outField; public LeftRightPanel() { // HINT: setLayout Manager // HINT: create a new JPanel leftButton = new JButton("Left"); leftButton.addActionListener(this); rightButton = new JButton("Right"); rightButton.addActionListener(this); // HINT: create Middle button, add event handler outField = new JTextField(10); // HINT: add three buttons to the JPanel // HINT: put everything together // JPanel goes in the CENTER position of LeftRightPanel // outField goes in the SOUTH position // HINT: these are not needed in the new layout add(leftButton); add(outField); add(rightButton); } public void actionPerformed(ActionEvent e) { JButton b = (JButton) e.getSource(); outField.setText( b.getText() ); } // actionPeformed() } // LeftRightPanel class package edu.buffalostate.cis425.sp24.put-your-username-here; /* * File: LeftRightApp.java * * Description: This program creates a LeftRightPanel and * adds it to the Frame's content pane and sets its size. * * Assignment: See LeftRightPanel.java * */ import javax.swing.*; public class LeftRightApp extends JFrame { public LeftRightApp() { getContentPane().add(new LeftRightPanel()); //register 'Exit upon closing' as a default close operation setDefaultCloseOperation( EXIT_ON_CLOSE ); } // LeftRightFrame() constructor public static void main(String args[]){ LeftRightApp aframe = new LeftRightApp(); aframe.setSize(600,400); aframe.setVisible(true); } // main() } // LeftRightFrame class
When you have this exercise ready for me to view and grade you should upload
your .java
file in the exercise Folder.
Exercise 15 - CDInterest (3 Points)
package edu.buffalostate.cis425.sp24.put-your-username-here; /* * File: CDInterestPanel.java * * Description: This class defines a GUI in a JPanel which contains * JTextFields for entering principal, interest rate, and years * and a JButton which when clicked will compute the maturity * value of a CD with those values and will display this value * in a JTextField. It uses the BankCD class. * * Assignment: 1) Change the layout of the component so that it looks * more "professional" (use a Layout Manager). You can * decide on the aesthetics... * 2) Add error checking to the inputs, so that data is * entered correctly. Catch errors and other bad input * 3) Add a TextField or TextArea object to display any * error messages from 2) above */ import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.text.NumberFormat; public class CDInterestPanel extends JPanel implements ActionListener { private JLabel prompt1; // Prompt for the principal. private JLabel prompt2; // Prompt for the interest rate. private JLabel prompt3; // Prompt for the number of years. private JTextField inputField1; // For principal. private JTextField inputField2; // For interest rate. private JTextField inputField3; // For number of years private JLabel resultLabel; // Labels the output private JTextField resultField; // The output private JButton button; // Click to compute the maturity value. public CDInterestPanel() { prompt1 = new JLabel("Enter the CD's initial principal:"); prompt2 = new JLabel("Enter the CD's interest rate (percent):"); prompt3 = new JLabel("Enter the number of years to maturity:"); resultLabel = new JLabel("The Maturity Value is:"); inputField1 = new JTextField(10); inputField1.setEditable(true); inputField2 = new JTextField(10); inputField2.setEditable(true); inputField3 = new JTextField(10); inputField3.setEditable(true); resultField = new JTextField(10); button = new JButton("Calculate the Maturity Value"); button.addActionListener(this); add(prompt1); add(inputField1); add(prompt2); add(inputField2); add(prompt3); add(inputField3); add(button); add(resultLabel); add(resultField); } // CDInterestPanel() /** * actionPerformed() handles clicks on the calculate button. * It inputs the data from the JTextFields, converts them to * numeric values and calls on the BankCD object to perform * the calculation. It translates the result into a currency format * and displays it in a JTextField. */ public void actionPerformed(ActionEvent e) { String inputString = inputField1.getText(); double principal = Double.parseDouble(inputString); inputString = inputField2.getText(); double rate = Double.parseDouble(inputString)/100.0; inputString = inputField3.getText(); double years = Double.parseDouble(inputString); BankCD cd = new BankCD(principal, rate, years); double maturityValue = cd.calcYearly(); NumberFormat dollars = NumberFormat.getCurrencyInstance(); String resultStr = dollars.format(maturityValue); resultField.setText(resultStr); } // actionPeformed() } // CDInterestPanel class package edu.buffalostate.cis425.sp24.put-your-username-here; /* * File: CDInterestApp.java * * Description: This program creates a CDInterestPanel and * adds it to the Frame's content pane and sets its size. * * Assignment: See CDInterestPanel.java file * */ import javax.swing.*; public class CDInterestApp extends JFrame { public CDInterestApp() { getContentPane().add(new CDInterestPanel()); //register 'Exit upon closing' as a default close operation setDefaultCloseOperation( EXIT_ON_CLOSE ); } // CDInterestFrame() constructor public static void main(String args[]){ CDInterestApp aframe = new CDInterestApp(); aframe.setSize(700,400); aframe.setVisible(true); } // main() } // CDInterestFrame class package edu.buffalostate.cis425.sp24.put-your-username-here; /* * File: BankCD.java * Author: Java, Java, Java * Description: This class calculates the maturity value of * a CD given its principal, interest rate and time period * in years. It contains a single method to perform * this task. */ public class BankCD { private double principal; // Purchase price of the CD. private double rate; // Yearly interest rate. private double years; // The period until maturity of CD. /** BankCD constructor assigns values to instance variables. * @param p -- a double representing the initial principal * @param r -- a double representing the interest rate * @param y -- a double representing the number of years. */ public BankCD(double p, double r, double y) { principal = p; rate = r; years = y; } /** * calcYearly() calculates the maturity value of a CD given * its principal, yearly interest rate, and maturity period. * It uses the formula a = p * (1 + r)^y * @param p -- a double representing the initial principal * @param r -- a double representing the interest rate * @param y -- a double representing the number of years * @return -- a doublein currency format is returned */ public double calcYearly() { return (principal * Math.pow(1 + rate, years)); } // calcYearly() /** * calcDaily() calculates the maturity value of a CD given * its principal, yearly interest rate, and maturity period * assuming daily compound interest. * It uses the formula a = p * (1 + r/365)^(365*y) * @param p -- a double representing the initial principal * @param r -- a double representing the interest rate * @param y -- a double representing the number of years * @return -- a doublein currency format is returned */ public double calcDailyly() { return (principal * Math.pow(1 + rate/365, years*365)); } // calcDaily() } // BankCD class
When you have this exercise ready for me to view and grade you should upload
your .java
file in the exercise Folder.
Exercise 16 - Calculator (3 Points)
package edu.buffalostate.cis425.sp24.put-your-username-here; /* * File: CalculatorGUI.java * * Description: This class creates an user interface for * a four-function integer calculator. The keys are arranged * in a 4 x 4 grid, which is at the center of the Frame's * border layout. At the north of the border layout is the * calculator's accumulator/display, implemented with a text * field. This version creates an instance of the Calculator * class which performs the operations associated with the * interface. See the actionPerformed() method. * * * Assignment: 1) Add four extra buttons to this calculator * - the new buttons should be: * SM, RM, CM, X^2 * * SM is short for Store Memory * RM is short for Recall Memory * CM is short for Clear Memory * X^2 is short for X*X * * Add these buttons to the bottom row of the display * * 2) Modify Calculator.java to add the extra functionality * * See HINTS for help */ import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.applet.Applet; public class CalculatorGUI extends JFrame implements ActionListener{ private final static int NBUTTONS = 16; // Constants - HINT add 4 extra buttons private JPanel keyPadPanel; // Panel to hold keyPad private JTextField accumulator; // Calculator's display private JButton keyPad[]; // Internal keyPad array private String label[] = // 16 keyPad Button Labels { "1","2","3","+", "4","5","6","-", "7","8","9","*", "C","0","=","/" }; // HINT add the label to the new buttons private Calculator calcMachine = new Calculator(); // The calculator /** * CalculatorGUI() constructor sets up the GUI. */ public CalculatorGUI(String title) { // Set up the keypad grid layout super(title); keyPadPanel = new JPanel(); keyPadPanel.setLayout(new GridLayout (4,4,1,1)); // HINT - bigger grid for the new buttons // Create an array of buttons keyPad = new JButton [NBUTTONS]; for (int k = 0; k < keyPad.length; k++){ // For each array slot Create a button keyPad[k] = new JButton( label[k] ); // And a listener for it keyPad[k].addActionListener(this); // And add it to the panel keyPadPanel.add(keyPad[k]); } // for // Set up the accumulator display accumulator = new JTextField("0",20); accumulator.setEditable (false); // Add components to the frame with Border layout getContentPane().setLayout(new BorderLayout(10, 10)); getContentPane().add("North", accumulator); getContentPane().add("Center", keyPadPanel); } // CalculatorGUI() /** * actionPerformed() handles all the action on the * calculator's keys. In this version the key plus the * current value of the calculator's display are passed * to the Calculator object, which performs an operation * and returns a result. */ public void actionPerformed (ActionEvent e) { // Get the button that was clicked JButton b = (JButton) e.getSource(); // And its label String key = b.getText(); String result = calcMachine.handleKeyPress(key, accumulator.getText()); accumulator.setText(result); } // actionPerformed() /** * main() creates an instance of the interface. */ public static void main( String args[] ) { // Make calculator look like a windows app try { // UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); // UIManager.setLookAndFeel("javax.swing.plaf.mac.MacLookAndFeel"); // UIManager.setLookAndFeel("javax.swing.plaf.motif.MotifLookAndFeel"); UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); // UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { System.out.println(e.getMessage()); } CalculatorGUI calc = new CalculatorGUI("Calculator"); calc.setSize(400,400); calc.setVisible(true); calc.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } // main() } // CalculatorGUI package edu.buffalostate.cis425.sp24.put-your-username-here; /* * File: Calculator.java * * Description: Implements a multifunction integer calculator. * Here's how it works. All calculations are performed using * two internal registers, the accumulator, which keeps a running * total of ongoing calculations, and the displayRegister, which * is set to the value displayed in the external display just * before an operation is performed. Inputs to the calculator * occur by pressing either digit keys, which signal that an * integer operand is being input, and operation keys (+ - * / C =), * which indicate that an operation should be performed. * * Control of the machine is managed by the handleKeyPress() * method. Two internal state variables are used to control * the machine. (1) The displayState variable keeps track of when * a new number is being started (REPLACE) and when incoming digits * should be APPENDed to the present value of the display. In APPEND * mode, it appends each digit typed to the external display. In * REPLACE mode, it replaces the external display with the digit * typed. (2) The opCode variable stores the current operation. * What makes control of the calculator somewhat tricky is that it * uses INFIX notation, so operations take the form: * Operand1 opCode Operand2 * The OpCode has to be remembered while Operand2 is being input. * The following example shows the state of these control variables * after each key press. The vertical lines (|) show when each * operation is done. For the expression 56 + 23 - 5 the calculator * does the addition (+) after the - key is pressed. It does the * subtraction (-) after the = key is pressed. The equal key resets * everything but the accumulator, which always stores the present * total. The accumulator is only reset after a Clear or an error. * * KEYPRESS: 5 6 + | 2 3 - | 5 = | * DISPLAY: 0 5 56 56 56 2 23 23 79 5 74 * DISPLAYREG: 0 56 0 23 0 5 0 * ACCUM: 0 0 56 56 56 79 79 74 * OPCODE -1 1 1 2 -1 * DISPLAYSTATE: R A R A R A R * * * Assignment - See CalculatorGUI.java for more information * See HINTs for more information * * */ import java.lang.*; public class Calculator { public final static int NOOP = -1; // Operations public final static int EQUAL = 0; public final static int ADD = 1; public final static int SUBTRACT = 2; public final static int MULTIPLY = 3; public final static int DIVIDE = 4; public final static int CLEAR = 5; public final static int APPEND = 0; // Display states public final static int REPLACE = 1; // HINT: add a new variable for the new memory function private int accumulator; // The actual accumulator // Internal memory for the visible textField private int displayRegister; // The operation that's waiting for Operand2 private int opCode; // State of the external display (REPLACE or APPEND) private int displayState; // Set true if divide-by-zero error private boolean error; /** * Calculator() constructor initializes the machine. */ public Calculator () { initialize(); } // constructor /** * initialize() resets the two registers and the opCode * and displayState variables. This is invoked initially * and then after each clear (C) and after each Error. */ private void initialize() { // Reset the machine's registers accumulator = 0; displayRegister = 0; // Replace the display with the next digit typed displayState = REPLACE; opCode = NOOP; // No current operation error = false; } // initialize() /** * keyToIntCode() converts key characters, such as '+', * to an integer code. * @return an int representing the key that was pressed */ private int keyToIntCode(char keyCh) { switch (keyCh) { case 'C': return CLEAR; case '=': return EQUAL; case '+': return ADD; case '-': return SUBTRACT; case '*': return MULTIPLY; case '/': return DIVIDE; } return -1; // Error Return } // keyToIntCode() /** * doCurrentOp() is invoked whenever C, =, +, -, *, or / * is pressed. Except for the Clear key, it performs * an operation, storing the result in the accumulator, * which is returned as the method's value. The Clear key * is treated as a special case and the machine is * reinitialized. For all other keys the opCode field * stores the operation that is waiting for its second * operand to be input. That operation is performed, * using the accumulator and displayRegister. After each * operation, the displayState is set to REPLACE, so the * next digit typed will start a new integer operand. * Note that EQUAL key, resets the opCode to NOOP, thus * beginning another complete INFIX operation. All other * keys (+ - / *) set the opCode to their keyCodes, thus * getting the machine ready to complete that operation * the next time an operator key is pressed. * @param keyCode -- an int representing one of EQUAL, ADD, * SUBTRACT, DIVIDE, MULT, CLEAR * @return an int representing the result of the calculation */ private int doCurrentOp(int keyCode) { // do current opCode if (keyCode == CLEAR) { initialize(); return accumulator; } switch (opCode) { case NOOP: accumulator = displayRegister; break; case ADD : accumulator = accumulator + displayRegister; break; case SUBTRACT : accumulator = accumulator - displayRegister; break; case MULTIPLY : accumulator = accumulator * displayRegister; break; case DIVIDE : if (displayRegister == 0) error = true; else accumulator = accumulator/displayRegister; break; } // switch if (keyCode == EQUAL) opCode = NOOP; // Reset opCode else opCode = keyCode; // Set up for next operation displayState = REPLACE; displayRegister = 0; return accumulator; } // doCurrentOp /** * handleKeyPress() handles all key presses. It * distinguishes two types of keys, digit keys, which * are used to create integer operands by appending digits, * and opCode keys such as '+' and 'C'. * @return a String giving the value that should be displayed * by the calculator. */ public String handleKeyPress(String keyStr, String external_display) { String resultStr; // Stores the result // HINT here is how you would add the Store Memory function ... now add the other three functions // if (keyStr.equals("SM")) { // Mem = Integer.parseInt(external_display); // resultStr = Integer.toString(Mem); // Return result // return resultStr; // } char keyCh = keyStr.charAt(0); // Convert the key label to a char if (Character.isDigit(keyCh)) { // If this was a digit key if (displayState == APPEND) // either append it resultStr = external_display + keyCh; else { // or use it to replace the display displayState = APPEND; resultStr = keyStr; } } else { // If not a digit key, it must be an opCode // Get display value displayRegister = Integer.parseInt(external_display); // Perform an operation int result = doCurrentOp(keyToIntCode(keyCh)); if (!error) resultStr = Integer.toString(result); // Return result else { resultStr = "Error"; initialize(); } } return resultStr; // return the result } // handleKeyPress() } // Calculator Class
When you have this exercise ready for me to view and grade you should upload
your .java
file in the exercise Folder.
Exercise 17 - Pong (3 Points)
package edu.buffalostate.cis425.sp24.put-your-username-here; /* * File: PongApp.java * * Description: In the game of pong a ball ricochets off * by the up the walls of a square. The paddle on the right wall * is controlled and down arrow keys. The ball bounces at a random * angle of the paddle and the walls. * DO NOT SUBMIT A SOLUTION THAT WAS DOWNLOADED - USE THIS TEMPLATE * * Assignment: 1) This is a fun game, so let's make it more exciting! * - Add to this program a mouse capability. As the mouse * is moved up and down, the paddle should move up and * down too. * 2) When a ball misses the paddle and hits the right wall, * the ball should disappear - the user will have to * launch another ball * 3) Add some kind of scoring capability to the game * - award the player skill points */ import javax.swing.*; import java.awt.*; import java.awt.event.*; // HINT: implement MouseMotionListener public class PongApp extends JFrame implements KeyListener { private Thread ball; private Paddle paddle; private int ComputerScore, UserScore; public final int BORDER=50; public final int SIZE=400; // HINT: Current MousePosition // int mouseX=-1; // int mouseY=-1; /** * Constructor: creates the ball and paddle objects, and registers as the * KeyListener. It also must requestFocus() so that it will receive * key events. */ public PongApp() { ComputerScore=UserScore=0; setSize(400,400); setBackground(Color.white); requestFocus(); // Required to receive key events addKeyListener(this); // HINT: // addMouseMotionListener(this); paddle = new Paddle(this); // Create the paddle ball = new Thread(new Ball(this)); // Create the ball //register 'Exit upon closing' as a default close operation setDefaultCloseOperation( EXIT_ON_CLOSE ); } // PongApp /** * startGame(): starts the ball (which causes it to draw) and draws the paddle. */ public void startGame() { ball.start(); repaint(); } /** * paint() starts the ball (which causes it to draw) and draws the paddle. */ public void paint (Graphics g ) { g.setColor(Color.white); g.fillRect(0,0,SIZE,SIZE); g.setColor(Color.red); // Draw the bouncing region g.drawRect(BORDER,BORDER,SIZE-2*BORDER,SIZE-2*BORDER); g.setColor(Color.blue); g.drawString("Score: User 0 Computer 0", 10,40); g.drawString("Press up/down arrow keys to move paddles",10,370); if (!ball.isAlive() ) g.drawString("Ball Died!, You Lose! - Hit Space", 10, 385); paddle.draw(); // And draw the paddle } // paint() /** * hitPaddle() is the callback routine called by ball to check whether it * hit the paddle. * @param p -- A Point giving the ball's location * @return -- a boolean set to true if the paddle and ball are touching */ public boolean hitPaddle(Point p) { Point paddleLoc = paddle.getLocation(); if ( p.x + Ball.SIZE >= paddleLoc.x && p.y >= paddleLoc.y && p.y <= paddleLoc.y + Paddle.SIZE) return true; else return false; } // hitPaddle() /** * informGame() is the callback routine called by ball when it dies * */ public void informGame() { // HINT: ball died - update score repaint(); return; } /** * keyTyped() is invoked every time a KeyEvent occurs. The getKeyChar() * method gets the value of the key that was pressed. Whenever the * spacebar is pressed, a new bouncing ball is introduced into the applet. */ public void keyTyped(KeyEvent e) { if (e.getKeyChar() == ' ') { // If spacebar pressed if (!ball.isAlive() ) { // and current ball is dead ball = new Thread(new Ball(this)); ball.start(); repaint(); } } } // keyType() /** * keyPressed() is invoked every time a KeyEvent occurs. It gets the key's code * and checks whether the up or down arrow keys were pressed. If so it moves * the paddle. */ public void keyPressed( KeyEvent e) { // Check for arrow keys int keyCode = e.getKeyCode(); if (keyCode == e.VK_UP) // Up arrow paddle.moveUp(); else if (keyCode == e.VK_DOWN) // Down arrow paddle.moveDown(); } // KeyPressed() public void keyReleased( KeyEvent e ) { } // keyReleased() - unused // HINT: // implement MouseMotionListener Methods: // // public void mouseDragged( MouseEvent e ) {} // // public void mouseMoved( MouseEvent e ) { // int x=e.getX(); // int y=e.getY(); // fill in rest of code // if mouse moves up call paddle.moveUp, otherwise call paddle.moveDown // } public static void main(String args[]) { PongApp p = new PongApp(); p.setVisible(true); p.startGame(); } // main() } // PongApp package edu.buffalostate.cis425.sp24.put-your-username-here; /* * File: Ball.java * * Description: This class defines a ball that bounces up and * down within an app. The "bouncing" is effected by repeatedly * drawing, and erasing and moving the ball in the run() method. * Note the use class constants in the program and the use of XOR mode * in the draw method. * * In this version of Ball, instead of starting every Ball in the center * of the bounce area, each ball is given a random x-coordinate. So each * bounces in its own vertical space. * * This version of Ball also keeps track of the location of the paddle. * The applet is used to mediate the connection between the paddle and the ball. * Whenever the ball hits the paddle, it bounces at a random angle. * * * * Assignment: See PongApp for more information * */ import javax.swing.*; import java.awt.*; public class Ball extends Thread implements Runnable { public static final int SIZE = 5; // Diameter of the ball private static final int DX = 5; // Number of pixels to move the ball private static final int DY = 5; // Number of pixels to move the ball private static final int MINDY = -4; // Used by randomizer: Vertical changes goes from private static final int MAXDY = 9; // -4 to +4, giving 9 discrete values private PongApp app; // Reference to the applet private int topWall, bottomWall; // Boundaries private int leftWall, rightWall; // Boundaries private int paddleLoc; // The horizontal location of the paddle private Point location; // Current location of the ball private int directionX = 1, directionY = 1; // Ball's x- and y-direction (1 or -1) private int deltaY; // Change in the Y coordinate private Color ballcolor; private boolean KeepBallAlive; /** * Ball() constructor sets a pointer to the applet and initializes the ball's location * at the center of the bouncing region */ public Ball(PongApp a) { app = a; Dimension gameArea = app.getSize(); // Define bouncing region rightWall = gameArea.width - app.BORDER - SIZE; // And location of walls leftWall = app.BORDER + 1; topWall = app.BORDER + 1; bottomWall = gameArea.height - app.BORDER - SIZE; paddleLoc = rightWall - app.BORDER; // Initial paddle location int xLoc = app.BORDER + (gameArea.width - app.BORDER)/2; // Pick a start xLoc location = new Point(xLoc, gameArea.height/2); // Set initial location ballcolor = Color.black; KeepBallAlive=true; } // Ball() /** * erase() erases the ball. */ public void erase() { synchronized (app) { Graphics g = app.getGraphics(); g.setColor(Color.white); g.fillOval(location.x, location.y, SIZE, SIZE); // erase g.dispose(); } } // erase() /** * draw() draws the ball. */ public void draw() { synchronized (app) { Graphics g = app.getGraphics(); g.setColor(ballcolor); g.fillOval(location.x, location.y, SIZE, SIZE); // draw g.dispose(); } } // draw() /** * move() changes the ball's vertical location (y-coordinate) by DY pixels. * It then checks if the ball has reached a boundary and if so reverses direction */ public void move() { location.x = location.x + DX * directionX; // Calculate a new location location.y = location.y + deltaY * directionY; if ( app.hitPaddle( location )) { // Check for paddle ricochet directionX = -directionX; // Change horizontal direction deltaY = MINDY + (int) (Math.random() * MAXDY); // Change vertical direction location.x = paddleLoc; // Adjust location } if (location.y > bottomWall) { // If ricochet directionY = -directionY; // reverse direction location.y = bottomWall; } if (location.y < topWall) { directionY = -directionY; // Reverse direction location.y = topWall; } if (location.x > rightWall ) { // HINT: hit right wall directionX = -directionX; location.x = rightWall; } if ( location.x < leftWall ) { directionX = -directionX; deltaY = MINDY + (int) (Math.random() * MAXDY); // CHANGE VERTICAL DIRECTION location.x = leftWall; } } // move() /** * run() repeatedly draws, erases and moves the ball */ public void run() { while (KeepBallAlive) { draw(); // Draw try { sleep(50); } catch (InterruptedException e) {} erase(); // Erase move(); // Move } // while app.informGame(); // HINT: ball died } // run() } // Ball package edu.buffalostate.cis425.sp24.put-your-username-here; /* * File: Paddle.java * * Description: This class represents a paddle for the Pong game. * The paddle is a vertical line segment located at the right boundary. * Its motion is controlled by the user via up/down arrow keys. Therefore * the paddle needs a reference to the app. The Paddle class contains * move() and draw() methods. * * Assignment: See PongApp for more information */ import java.awt.*; public class Paddle { public static final int SIZE = 20; // Size of Paddle private static final int DELTA = 10; // Size of each move // private static final int BORDER = 50; private PongApp app; // Reference to the applet private Point location; private Dimension gameArea; /** * Paddle() constructor is passed a reference to the applet, which it * uses to determine the dimensions of the game area. */ public Paddle (PongApp a) { app = a; gameArea = app.getSize(); location = new Point(gameArea.width - SIZE - app.BORDER, gameArea.height/2); } // Paddle() /** * getLocation() is returns the paddle's current location * @return -- a Point giving the paddle's location */ public Point getLocation() { return location; } /** * erase() redraws the paddle (line segment) each time it is called. * */ public void erase() { synchronized(app) { Graphics g = app.getGraphics(); g.setColor(Color.white); g.drawLine (location.x, location.y, location.x, location.y + SIZE); g.drawLine (location.x+1, location.y, location.x+1, location.y + SIZE); g.dispose(); } } // erase /** * draw() redraws the paddle (line segment) each time it is called. * Note the use of XOR mode, which enables this same method to be used * to draw or erase the paddle. */ public void draw() { synchronized(app) { Graphics g = app.getGraphics(); g.setColor(Color.black); g.drawLine (location.x, location.y, location.x, location.y + SIZE); g.drawLine (location.x+1, location.y, location.x+1, location.y + SIZE); g.dispose(); } } // draw() /** * moveUp() moves the paddle up by a fixed DELTA */ public void moveUp () { erase(); // Erase present paddle if (location.y > app.BORDER ) location.y -= DELTA; draw(); // Draw new paddle } // moveUp() /** * moveDown() moves the paddle down by a fixed DELTA */ public void moveDown() { erase(); // Erase current paddle if (location.y + SIZE < gameArea.height - app.BORDER) location.y += DELTA; draw(); // Draw new paddle } // moveDown() } // Paddle
When you have this exercise ready for me to view and grade you should upload
your .java
file in the exercise Folder.
Exercise 18 - Bounce (3 Points)
package edu.buffalostate.cis425.sp24.put-your-username-here; /* * File: BounceApp.java * * Description: This version allows the user to introduce new balls * by clicking the spacebar. It implements the KeyListener interface. * * * Assignment: 1) Modify this program so that each bouncing ball is * a different shape, size, and color * */ import javax.swing.*; import java.awt.*; import java.awt.event.*; public class BounceApp extends JFrame implements KeyListener { public final int SIZE=500; public final int BORDER=50; private Thread ball; /** * init() gets the focus for key events and registers the app * as a KeyListener. */ public BounceApp() { setSize(500,500); getContentPane().setBackground(Color.white); requestFocus(); // Required to receive key events addKeyListener(this); //register 'Exit upon closing' as a default close operation setDefaultCloseOperation( EXIT_ON_CLOSE ); } public void startApp() { ball = new Thread(new Ball(this)); // Create and start the ball ball.start(); repaint(); } /** * paint() paints a red rectangle for the bouncing region and creates the * first bouncing ball. */ public void paint(Graphics g ) { g.setColor(Color.white); g.fillRect(0,0,SIZE,SIZE); g.setColor(Color.red); // Draw the bouncing region g.drawRect(BORDER,BORDER,SIZE-2*BORDER,SIZE-2*BORDER); // actually (50,50,400,400) g.drawString("Hit space bar to start a new ball", 10, 40); } // paint() /** * keyTyped() is invoked every time a KeyEvent occurs. The getKeyChar() * method gets the value of the key that was pressed. Whenever the * spacebar is pressed, a new bouncing ball is introduced into the applet. */ public void keyTyped(KeyEvent e) { if (e.getKeyChar() == ' ') { // If spacebar pressed ball = new Thread(new Ball(this)); ball.start(); } } // keyType() public void keyReleased( KeyEvent e) {} // Unused part of KeyListener interface public void keyPressed( KeyEvent e) {} // Unused public static void main(String args[]) { BounceApp b = new BounceApp(); b.setVisible(true); b.startApp(); } // main() } // BounceApp package edu.buffalostate.cis425.sp24.put-your-username-here; /* * File: Ball.java * * Description: This class defines a ball that bounces up and * down within an applet. The "bouncing" is effected by repeatedly * drawing, and erasing and moving the ball in the run() method. * Note the use class constants in the program * * In this version of Ball, instead of starting every Ball in the center * of the bounce area, each ball is given a random x-coordinate. So each * bounces in its own vertical space. Also, the balls bounce at random * angles off of the four walls. The randomness is introduced by changing * the y-coordinate by a random amount between -4 and +4 each time the * ball bounces off either the right or left wall. This changes the angle * of the ball's motion. * * Assignment: See BounceApp for more information * * */ import javax.swing.*; import java.awt.*; public class Ball extends Thread implements Runnable { // HINT create ovals rather than a circle // need SizeX, SizeY of two different lengths private static final int SIZE = 5; // Diameter of the ball private static final int DX = 5; // Number of pixels to move the ball private static final int DY = 5; // Number of pixels to move the ball // private static final int BORDER = 50; // A 50 pixel border around drawing area private static final int MINDY = -4; // Used by randomizer: Vertical changes goes from private static final int MAXDY = 9; // -4 to +4, giving 9 discrete values private BounceApp app; // Reference to the app private int topWall, bottomWall; // Boundaries private int leftWall, rightWall; // Boundaries private Point location; // Current location of the ball private int directionX = 1, directionY = 1; // Ball's x- and y-direction (1 or -1) private int deltaY; // Change in the Y coordinate private Color ballcolor; /** * Ball() constructor sets a pointer to the app and initializes the ball's location * at the center of the bouncing region */ public Ball(BounceApp f) { app = f; Graphics g; Dimension gameArea = app.getSize(); // Define bouncing region rightWall = gameArea.width - app.BORDER - SIZE; // And location of walls leftWall = app.BORDER + 1; topWall = app.BORDER + 1; bottomWall = gameArea.height - app.BORDER - SIZE; int xLoc = app.BORDER + (int)(Math.random() * (gameArea.width - 2*app.BORDER)); // Pick a random xLoc location = new Point(xLoc, gameArea.height/2); // Set initial location // HINT: Create a new random color ballcolor = new Color( 0, 0, 0 ); synchronized( app ) { // make sure one ball at a time is allowed to access canvas g=app.getGraphics(); g.setColor(ballcolor); g.dispose(); } // HINT: Create a new oval shape ( two values ) // SizeX=random value // SizeY=random value } // Ball() /** * erase() erases the ball * */ public void erase() { synchronized(app) { // only one ball at a time is allowed to do drawing Graphics g = app.getGraphics(); g.setColor(Color.white); g.fillOval(location.x, location.y, SIZE, SIZE); // erase g.dispose(); } } // erase() /** * draw() draws ball */ public void draw() { synchronized(app) { // only one ball at a time is allowed to do drawing Graphics g = app.getGraphics(); g.setColor(ballcolor); // HINT: set Oval to random SizeX, SizeY values g.fillOval(location.x, location.y, SIZE, SIZE); // draw g.dispose(); } } // draw() /** * move() changes the ball's vertical location (y-coordinate) by DY pixels. * It then checks if the ball has reached a boundary and if so reverses direction */ public void move() { location.x = location.x + DX * directionX; // Calculate a new location location.y = location.y + deltaY * directionY; if (location.y > bottomWall) { // If ricochet directionY = -directionY; // reverse direction location.y = bottomWall; } if (location.y < topWall) { directionY = -directionY; // Reverse direction location.y = topWall; } if (location.x > rightWall ) { directionX = -directionX; deltaY = MINDY + (int) (Math.random() * MAXDY); // CHANGE VERTICAL DIRECTION location.x = rightWall; } if ( location.x < leftWall ) { directionX = -directionX; deltaY = MINDY + (int) (Math.random() * MAXDY); // CHANGE VERTICAL DIRECTION location.x = leftWall; } } // move() /** * run() repeatedly draws, erases and moves the ball */ public void run() { while (true) { draw(); // Draw try { sleep(50); } catch (InterruptedException e) {} erase(); // Erase move(); // Move } // while } // run() } // Ball
When you have this exercise ready for me to view and grade you should upload
your .java
file in the exercise Folder.
Exercise 19 - ColorPicker (3 Points)
package edu.buffalostate.cis425.sp24.put-your-username-here; /* * File: ColorPicker.java * * Description: This app illustrates the use of the * java.awt.Color class. It lets the user type red, green and * blue (RGB) values into text fields, and displays the resulting * color both as a font color and as a colored rectangle. * This version of ColorPicker uses programmer defined IntFields * which throw an out-of-range exception if the values input are * not between 0 and 255. The only changes required occur in the * declarations for the IntFields, in the init() method where the * IntFields are instantiated, and in the actionPerformed() method * the the getInt() method is used to retrieve their data. * * * Assignment: 1) Run this program to see how it works * 2) Modify this program so that it uses JSliders to * select the range of colors. Arrange the JSliders * so they are oriented horizontally and stacked using * a grid layout: * * |-------- slider1 ----------| * |-------- slider2 ----------| * |-------- slider3 ----------| * * - See the example in the SliderExample folder to get started */ import javax.swing.*; import java.awt.*; import java.awt.event.*; // HINT: use ChangeListener rather than ActionListener public class ColorPicker extends JFrame implements ActionListener { private IntField redIn, greenIn, blueIn; private JLabel R = new JLabel("R:"), G = new JLabel("G:"), B = new JLabel("B:"); private JPanel controls = new JPanel(); private Canvas canvas = new Canvas(); /** * init() sets up the app's interface. A (default) border layout * is used, with the controls at the north and the drawing canvas * in the center. */ public ColorPicker() { initControls(); getContentPane().add(controls, "North"); getContentPane().add(canvas, "Center"); canvas.setBorder(BorderFactory.createTitledBorder("The Color Display")); getContentPane().setBackground(Color.white); setSize(250,250); //register 'Exit upon closing' as a default close operation setDefaultCloseOperation( EXIT_ON_CLOSE ); } /** * initControls() arranges the app's control components in a separate * JPanel, which is placed at the north border. The controls consist of * three JTextFields into which the user can type RGB values. */ private void initControls() { // HINT create 3 sliders instead of IntFields redIn = new IntField(4, 0, 255); // Create 3 integer textfields greenIn = new IntField(4, 0, 255); // that accept values between blueIn = new IntField(4, 0, 255); // 0 and 255 redIn.setText("128"); // And set their initial text values greenIn.setText("128"); blueIn.setText("128"); //HINT: addChangeListener(this) instead of addActionListener() redIn.addActionListener(this); // Give them listeners greenIn.addActionListener(this); blueIn.addActionListener(this); // HINT use a GridLayout(6,1) with sliders controls.setLayout( new FlowLayout()); controls.setBorder(BorderFactory.createTitledBorder("Type in values for RGB")); controls.add(R); controls.add(redIn); // Add prompts and textfields controls.add(G); controls.add(greenIn); controls.add(B); controls.add(blueIn); } // initControls() // HINT: if you are not using IntField, then you do not need actionPerformed() /** * actionPerformed() handles the app's actions. No matter which action * led to the method call, integer values are read from the RGB text fields * and passed along as a new color to the canvas object. The app is then * repainted. If the user types an invalid value into the IntField, a message * dialog is used to print an error message. */ public void actionPerformed(ActionEvent e) { try { int r = redIn.getInt(); // Get user's inputs int g = greenIn.getInt(); int b = blueIn.getInt(); canvas.setColor(new Color(r, g, b)); // If no error, reset the canvas's color repaint(); // and repaint the app } catch (IntOutOfRangeException ex) { JOptionPane.showMessageDialog(this, "The input value must be between 0 and 255"); } } // actionPerformed() // HINT: add the following //public void stateChanged( ChangeEvent e) { // int r, g, b; // r=redIn.getValue(); // fill in rest of code //} public static void main(String args[]) { ColorPicker c = new ColorPicker(); c.setVisible(true); } // main() } // ColorPicker package edu.buffalostate.cis425.sp24.put-your-username-here; /* * File: Canvas.java * * Description: This class implements a drawing canvas as * a subclass of JPanel. It is used with the ColorPicker applet. * It simply displays various shades of a given Color. * * Assignment: See ColorPicker.java * */ import javax.swing.*; import java.awt.*; public class Canvas extends JPanel { private final int HREF = 40, VREF = 55; // Reference points private final int WIDTH = 40, HEIGHT = 50; // Rectangle dimensions private final int HGAP = 70, VGAP = 60; // Spacing constants private Color color = Color.gray; /** * setColor() changes the default color for the Canvas. * @param c -- a Color */ public void setColor(Color c) { color = c; } /** * paintComponent() is called each time the canvas needs to be * painted. It draws three strings and three rectangles in * various shades of the Canvas's current color. * @param g -- the Canvas's Graphics object */ public void paintComponent(Graphics g) { super.paintComponent(g); // Make the panel opaque g.setColor(color); // Set the pen's color g.drawString(color.toString(), HREF, VREF-15 ); // Draw the color's RGB's g.fillRect(HREF, VREF, WIDTH, HEIGHT); // Color a rectangle g.drawString("color", HREF, VREF+VGAP); g.setColor(color.brighter()); // Brighten the color g.fillRect(HREF+HGAP, VREF, WIDTH, HEIGHT); g.drawString("brighter", HREF+HGAP, VREF+VGAP); g.setColor(color.darker()); // Darken the color g.fillRect(HREF+HGAP*2, VREF, WIDTH, HEIGHT); g.drawString("darker", HREF+HGAP*2, VREF+VGAP); } // paintComponent() } // Canvas package edu.buffalostate.cis425.sp24.put-your-username-here; /* * File: IntField.java * * Description: This version of IntField has both an upper and lower bound * associated with it. The user must type a number within these bounds * into the field. A programmer defined exception, IntOutOfRangeException, is * thrown if the bound is exceeded. * Note that upperBound and lowerBound are set initially to MAX and MIN possible * values respectively. This allows the field to accept any numeric input if * its first constructor is used. * * Assignment: See ColorPicker.java */ import javax.swing.*; public class IntField extends JTextField { private int upperBound = Integer.MAX_VALUE; private int lowerBound = Integer.MIN_VALUE; /** * IntField() constructor merely invokes its superclass * constructor, in this way inheriting all the properties * of a JTextField. */ public IntField (int size) { super(size); } /** * This IntField() constructor sets the field's two bounds. */ public IntField(int size, int min, int max) { super(size); upperBound = max; lowerBound = min; } /** * getInt() converts the field's text to an int and returns it. * This version also checks that the field's bounds are not exceeded * and raises an exception if one or the other is. The method also makes clear that * a NumberFormatException could be thrown. This would happen if the * user types a value that is not a valid integer. * @return an int representing the integer typed into the text field */ public int getInt() throws NumberFormatException, IntOutOfRangeException { int num = Integer.parseInt(getText()); if (num > upperBound) throw new IntOutOfRangeException(upperBound); else if (num < lowerBound) throw new IntOutOfRangeException(lowerBound); return num; } // getInt() } // IntField package edu.buffalostate.cis425.sp24.put-your-username-here; /* * File: IntOutOfRangeException.java * Author: Java, Java, Java * Description: This Exception subclass is invoked when an * integer value exceeds its bound. */ public class IntOutOfRangeException extends Exception { public IntOutOfRangeException(int Bound) { super("The input value exceeds the bound " + Bound); } }
When you have this exercise ready for me to view and grade you should upload
your .java
file in the exercise Folder.
Communication
This is a hybrid course which will have in-class meetings for discussions and also utilize Brightspace for chapter-based discussions and tests. Students are expected to login at minimum multiple times each week for course announcements, assignments, quizzes, discussions,etc.
Faculty/Instructor: I can be reached by e-mail with questions or for guidance that are concerned with this course. You should expect that I will reply to your message within 1-2 business days. Specific course-related questions (textbook, tests, discussions, etc.) should be posted in Brightspace so everyone can benefit from the questions and answers.
Students: If you have multiple e-mail accounts, please be sure that you access (or forward) your Buffalo State e-mail. Your Buffalo State e-mail is the account I will use to send course-related materials.
Netiquette
About Cell Phones, IPhones and IStuff ("HANDS OFF POLICY")
Before entering the classroom, turn off all cell phones, SmartPhones, IStuff, and other electronic
devices. These devices are disruptive and their use during a lecture is rude to the class and instructor.
- No electronic devices should be in your hands during class. This means no fiddling with your phones, reading/sending text messages, etc.
- If you are expecting an important phone call or are compelled to play with Apps, do not attend class.
- If you feel you have a legitimate reason to use an electronic device in the classroom, see me to obtain explicit permission.
This course utilizes BlackboardLearn to facilitate online communication between course participants. Please keep in mind the following "Rules of Netiquette" when communicating online.
- The rules of the classroom are the same regardless of location. Remember just because you're interacting online, doesn't mean you stop having respect for your professors, and fellow classmates. You're communicating with a real person, not a computer screen.
- Remember your audience. When communicating online it's important to remember who you're communicating with. When sending a message to a professor, please refrain from using "text speak". For example, Shakespeare never intended for you to type "2B or not 2B". Also, stay away from typing in all capital letters; it will appear as if you're shouting.
- Avoid b language. Language can easily be misinterpreted in an online setting. Be sure to review your work before submitting, making sure the reader won't be able to misinterpret it as b, or offensive. Sarcasm doesn't translate well online. Your audience can't see your facial expressions, or body language. Try to be as straight forward and professional as possible.
- Read everything, twice. Be sure to thoroughly read all course materials before beginning to work on your assignments. If you have a question, or need clarification, re-read the materials. You may have glanced over an important detail the first time. If you're still having difficulties, then e-mail your professor.
- Review all materials before submitting. When responding to discussion board posts, be sure to read all previous postings before you post your own. This way you won't duplicate someone else's comments. Also, it's a good idea to write, and save your work in Microsoft Word first. In case of a technical issue, you have a backup copy.
Policy Regarding Absences, Attendance, Assignments, Exams, etc.
- Class Attendance and Absences
As many online activities will be completed throughout the semester, participation in our Brightspace Discussion Forums is expected. In the case of exceptional circumstances that result in you not being able to participate in a timely manner, you must contact me prior to the start of your absence (either by e-mail or by leaving a telephone message). Please be aware that a prolonged absence from Brightspace under these circumstances does not excuse you from any required assignments. - Late Assignments
All assignments are due at the designated time and due date. Late assignments will not be accepted. If there are circumstances that will preclude you from turning in assignments on the due date, it is imperative that you discuss the situation with the instructor prior o the due date. - Exams and Final Exam
See grading for information about quizzes and exams in this course. - Disability Policy
If you have any disability which requires reasonable accommodations to enable you to participate in this course, please contact the Disability Services Office, 120 South Wing, (716) 878-4500, and also the instructor of this course during the first week of class. DSO will provide you with information and review appropriate arrangements for reasonable accommodations. Buffalo State Disability Services Office Web Site - Academic Integrity
Reference: Academic Standards Web SiteStudents who are suspected of academic dishonesty will be dealt with severely in accordance with the Department and College Policy. This may include a grade of 0 for an assignment and/or failure in a course.
- Academic Dishonesty: Actions that compromise academic integrity include, but are not
limited to the following examples:
- Previously submitted work: submitting academically required material that has been previously submitted - in whole or in substantial part - in another course, without prior and expressed consent of the instructor.
- Plagiarism. Copying or receiving material from any source and submitting that material as one's own, without acknowledging and citing the particular debts to the source (quotations, paraphrases, asic ideas), or in any other manner representing the work of another as one's own.
- Cheating. Soliciting and/or receiving information from, or providing information to, another student or any other unauthorized source (including electronic sources such as cellular phones and PDAs), with the intent to deceive while completing an examination or individual assignment.
- Falsification of academic materials. Fabricating laboratory materials, reports, or any forms of computer data; forging an instructor's name or initials; resubmitting an examination or assignment for re-evaluation which has been altered without the instructor's authorization; or submitting a report, paper, materials, computer data, or examination (or any considerable part thereof) prepared by any person other than the student responsible for the assignment.
- Misrepresentation of documents. Forgery, alteration, or misuse of any College or Official document, record, or instrument of identification.
- Confidential academic materials. Procurement, distribution or acceptance of examinations r laboratory results without prior and expressed consent of the instructor.
- Selling academic assignments. No person shall sell or offer for sale to any person enrolled at the Buffalo State any academic assignments, or any inappropriate assistance in the preparation, research, or writing of any assignment, which the sellers knows, or has reason to believe, is intended for submission in fulfilled of any course or academic program requirement.
- Purchasing academic assignments. No person shall purchase an academic assignment intended for submission in fulfillment of any course or academic program requirement.
Good Luck!
Jim...
View Jim Gerland's
profile