Object methods

advertisement
CIS1068 Practice Problems: Object & methods
1. Tracing programs
a.
What does the class below print to the screen?
import java.util.Arrays;
public class MysteryClass1
{
public static void main(String [] args)
{
Point[] p = {new Point(2,4), new Point(3,5), new Point(9,11)};
mystery1(p);
System.out.println(Arrays.toString(p));
p = mystery2(p);
System.out.println(Arrays.toString(p));
}
public static void mystery1(Point [] ps)
{
for(int i=0; i<ps.length; i++) {
ps[i].setLocation(ps[i].x + i, ps[i].y);
}
}
public static Point [] mystery2(Point [] ps)
{
Point [] ret = new Point[ps.length];
for(int i=0; i<ps.length; i++) {
ps[i].translate(-1, 1);
}
return ret;
}
}
public class Point
{
public double x;
public double y;
// the point’s x-coordinate
// the point’s y-coordinate
public Point(double x, double y)
// constructor of point
{
…
}
public double distance (Point p)
// how far away this point is from point p
{
…
}
public void setLocation (double x, double y)
// sets the point’s x and y to the given values
{
…
}
public void translate (double dx, double dy)
// adjusts the point’s x and y by the given amounts
{
…
}
}
b. Answer the questions below about the following class:
public class MysteryClass2
{
public static void main(String [] args)
{
Point p = new Point(3, 7);
Point p2 = new Point(5, 9);
p2 = mystery(p, p2);
// POINT 1
}
public static Point mystery(Point p1, Point p2)
{
Point ret = new Point(p1.x, p1.y);
p1.translate(p2.x, p2.y);
p2.setLocation(-5, 5);
// POINT 2
return ret;
}
}
Question: What are the values of all variables at POINT 1 in main?
Question: What are the values of all variables at POINT 2 in mystery?
2. Primitive types and methods
a. Fill out the class below so that it prints out 5 squares of different sizes on the screen, consisting of some
ASCII character.
public class SquarePrinter {
public static void main(String [] args)
{
printSquare(10);
printSquare(15);
for(int i=4; i<16; i+=5) {
printSquare(i);
}
}
// your code here
}
b.
Change the printSquare method to a printRectangle method, where each rectangle's height might be
different from the width. Modify the main method to call the printRectangle method instead of
printSquare.
3. Object methods
a.
Write a class ArrayOperation with an array that is initiated with a sequence of integers in its
constructor. The program of constructor will check with the user how many numbers are needed and
then store them in a private attribute (private int [ ] data). The class should also have the following
methods (instance):
 getTotal(), which should return total of the values in the array data.
 getAverage(), which should return the average of the values in the array data.
 getHighest(), which should return the highest value in the array data.
 getLowest(), which should return the lowest value in the array data.
 Accessor (toString) and mutator (setData) of such an array data, so that the entire array
can be return and any element of such an array can be updated.
Then write another class ArrayOperations with the only static main method. In that main method,
implement a test case that can cover all the above methods (constructor, accessor, mutator, and other 4
methods). For instance:
Scanner kb = new Scanner(System.in);
System.out.println("Before the test, build your array object for ? integers!");
System.out.print("Input the number of integers:");
int index = kb.nextInt();
ArrayOperation a = new ArrayOperation(index);
String str = "";
kb.nextLine(); // to consume the end of line for the above print, not println
System.out.println("Do you want to start the test, Y/N or y/n?");
str = kb.nextLine();
while((str.toUpperCase()).charAt(0)=='Y'){
System.out.println("1: what are in the array now?");
System.out.println("2: change the value of an element.");
System.out.println("3: total of the array values.");
System.out.println("4: average of the array values.");
System.out.println("5: highest of the array values.");
System.out.println("6: lowest of the array values.");
System.out.println("other number: quit!");
int event = kb.nextInt();
switch(event){
case 1:
System.out.println(a); // accessor of data toString
break;
case 2:
System.out.print("Please key-in the position:");
index = kb.nextInt();
System.out.print("Please key-in the new value:");
int value = kb.nextInt(); // the value inputed can be out of range!
a.setData(index, value); // mutator
System.out.print("After the change:");
System.out.println(a);
break;
case 3:
System.out.println("Total of the values is: "+(a.getTotal()));
break;
case 4:
System.out.println("Average of the values is: "+a.getAverage());
break;
case 5:
System.out.println("Highest of the values is: "+a.getHighest());
break;
case 6:
System.out.println("Lowest of the values is: "+a.getLowest());
break;
}
if(event < 1 || event >6 ) str = "N";
else{
System.out.println("Do you want to continue the test, Y/N or y/n?");
kb.nextLine(); //consume the print-out information for the below reading
str = kb.nextLine();
}
}
b.
Write a class Account with a method that accepts a charge account as its argument. The method should
determine whether the argument number is valid by comparing it to the following list of valid charge
account numbers:
5658845,4250125,7895122,8777541,8451277,1302850,
8080152,4562555,5552012,5050552,7825877,1250255,
1005231,6545231,3852085,7576651,7881200,4581002
These numbers should be stored in an array that is initiated in the class as a private attribute. If the
number is in the array, the method should return true, otherwise, return false.
Then write another class AccountApplication with the only static main method. In that main method,
implement a test of such a method by asking the user to enter a charge account number. The program
should display a message indicating whether the number is valid or invalid.
c.
Write a class DirverExam that has a private array of char initiated to hold the correct answers of the
local driver’s license exam:
1. B, 2. D, 3. A, 4. A, 5. C, 6. A, 7. B, 8. A, 9. C, 10. D, 11. B, 12. C, 13. D, 14. A, 15. D, 16. C, 17. C,
18. B, 19. D, 20. A
The class must have another private array to save the student’s answers. The class should have the
constructor to allow this student to input all answers (by nextLine().toUpperCase().charAt(0)). This
class also should have the following methods (public):
 Passed ( ), returns true if the student passed the exam, or false if the student failed. The exam has
20 multiple questions. A student must correctly answer 15 of the 20 questions to pass the exam.
 totalCorrect ( ), returns the total number of correctly answered questions.
 totalIncorrect ( ), returns the total number of incorrectly answered questions.

questionsMissed ( ), returns an array of integers that contains the numbers of the questions that the
student missed. Note that in the student score array, any character other than ‘A’, ‘B’, ‘C’, or ‘D’
will be treated as an answer missed.
Then write a class DL with the only static main method. In that main method, implement a test case
that can test all the above methods. For instance:
public static void main(String[] args) {
DriversExam d = new DriversExam();
System.out.println("Has this student passed the test? "+d.passed());
System.out.println("# of questions correctly answered: "+…;
}
d.
Write a class Payroll that uses the following arrays as fields (private):
 employeeId, an array of 7 integers to hold employee ID. The array should be initialized with the
following numbers: 5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 7580489.
 hours, an array of 7 integers to hold the number of hours worked by each employee.
 payRate, an array of 7 doubles to hold each employee’s hourly pay rate.
 wages, an array of 7 doubles to hold each employee’s gross wages.
This class should have all accessors and mutators of these fields (on each array element). Assume the
data in each array is related through the subscript. For example, the number in element 0 of the hours
array should be the number of hours worked by the employee whose ID number is stored in element 0
of the employeeId array. That same employee’s pay rate should be stored in element 0 of the payRate
array. Your class should also have a method that accepts an employee’s ID as an argument and returns
the gross pay for that employee.
Then write a class PayrollApplication with the only static main method. In that main method,
implement a test case that can cover all the above accessors and mutators. Note that negative values for
hours or numbers less than 6.00 for pay rate are not accepted. For instance:
Payroll a = new Payroll();
Scanner kb = new Scanner(System.in);
a.setAll();
System.out.println(a);
System.out.println("Do you want to start the test, Y/N or y/n?");
String str = kb.nextLine();
while((str.toUpperCase()).charAt(0)=='Y'){
System.out.println("1: Dispaly the whole table.");
System.out.println("2: Reset the whole table.");
System.out.println("3: Dispaly the record of a person with index.");
System.out.println("4: Dispaly the record of a person with his/her ID.");
System.out.println("5: Update any individual record.");
System.out.println("other number: quit!");
int event = kb.nextInt();
int index, id;
switch(event){
case 1:
System.out.println(a);
break;
case 2:
a.setAll();
break;
case 3:
System.out.println("Input Index please:");
index = kb.nextInt();
System.out.println("Hours:"+a.getHours(index));
System.out.println("PayRate:"+a.getPayRate(index));
System.out.println("Wages:"+a.getWages(index));
break;
case 4:
System.out.println("Input employee ID please:");
id = kb.nextInt();
index=a.getIndex(id);
if(index!=-1){
System.out.println("Hours:"+a.getHours(index));
System.out.println("PayRate:"+a.getPayRate(index));
System.out.println("Wages:"+a.getWages(index));
}
else System.out.println("Either not found or out of range.");
break;
case 5:
index=-1;
System.out.println("1. Update hours with index.");
System.out.println("2. Update hours with employee ID.");
System.out.println("3. Update payRate with index.");
System.out.println("4. Update payRate with employee ID.");
System.out.println("Other number. Back to Main menu.");
event = kb.nextInt();
while(event>=1&&event <=4){
if(event==1||event ==3){
System.out.println("Input Index please:");
index = kb.nextInt();
}
else if (event ==2||event==4){
System.out.println("Input ID please:");
id = kb.nextInt();
index=a.getIndex(id);
}
else index = -1;
if(index!=-1){
if(event==1)a.setHours(index);
else
a.setPayRate(index);
a.setWages(index);
System.out.println("Wages:"+a.getWages(index));
System.out.println();
}
else System.out.println("Either not found or out of range!");
System.out.println("1. Update hours with index.");
System.out.println("2. Update hours with employee ID.");
System.out.println("3. Update payRate with index.");
System.out.println("4. Update payRate with employee ID.");
System.out.println("Other number. Back to Main menu.");
event = kb.nextInt();
}
}
if(event < 1 || event >5 ) str = "N";
else{
System.out.println("Do you want to continue the test, Y/N or y/n?");
kb.nextLine(); //consume the print-out information for the below reading
str = kb.nextLine();
}
}
e.
Write a class GradeBook that uses the following arrays as private fields:
 names, a string array to hold five students’ names
 grades, an array of 5 characters to hold the five students’ letter grades.

testScores, a 2-dimentional array to hold 4 test scores for each of five students.
The class should have a constructor for the user to enter each student’s name and his or her four test
scores. The constructor will use an associate method (private double getAvg(int index)) to obtain the
average test score for student index, and then convert to a letter grade into grades[index] by the other
(private void setGrade). This method will use the following Numeric-To-Letter-Grade Scale: 90-100
A, 80-89 B, 70-79 C, 60-69 D, 0-59 F. The accessor (public String toString) will return a string that
carries all private information needed to access.
Then write a class Grade with the only static main method. In that main method, implement a test case
that can cover all the above accessor. Note that any score less than 0 or greater 100 is not acceptable.
When constructor is executed in the object initialization, the program will allow the user to enter each
student’s name and his or her four test scores. After that, the program should display each student’s
name, average score, and letter grade.
Download