0% found this document useful (0 votes)
9 views5 pages

Java Classes and Objects Tutorial

The document contains 5 questions asking students to write Java programs to: 1) Use the GregorianCalendar class to display the current date and a date represented by a long value. 2) Create a Rectangle class with methods to return area, perimeter and draw a rectangle based on length and width. 3) Create a Vehicle class with properties like speed and brand, and methods to modify and return speed. 4) Create a PhoneKeyPad program to convert a string to digits based on a phone keypad mapping. 5) Create a QuadraticEquation class to calculate the discriminant and roots of a quadratic equation based on coefficients a, b, c.

Uploaded by

Mr. X
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views5 pages

Java Classes and Objects Tutorial

The document contains 5 questions asking students to write Java programs to: 1) Use the GregorianCalendar class to display the current date and a date represented by a long value. 2) Create a Rectangle class with methods to return area, perimeter and draw a rectangle based on length and width. 3) Create a Vehicle class with properties like speed and brand, and methods to modify and return speed. 4) Create a PhoneKeyPad program to convert a string to digits based on a phone keypad mapping. 5) Create a QuadraticEquation class to calculate the discriminant and roots of a quadratic equation based on coefficients a, b, c.

Uploaded by

Mr. X
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Tutorial 4 Classes and Objects

NOTE: Put all the source code and answers into a word file, and upload the word file (just
ONE Word file! name it with “your ID_name_date”, e.g. 20191963****_***_20201028.doc).

Attempt ALL questions. Each question is worth 2 marks, with 10 marks in total.

1. Java API has the GregorianCalendar class in the [Link] package, which
you can use to obtain the year, month, and day of a date. The no-arg
constructor constructs an instance for the current date, and the methods
get([Link]), get([Link]), and
get(GregorianCalendar.DAY_OF_MONTH) return the year, month, and day.
Write a program to perform two tasks:
■ Display the current year, month, and day.
■ The GregorianCalendar class has the setTimeInMillis(long), which can be
used to set a specified elapsed time since January 1, 1970. Set the value to
1234567898765L and display the year, month, and day.

 SOURCE CODE (TEXT)

 EXECUTION RESULTS (TEXT OR SNAPSHOTS)

 DISCUSSION AND CONCLUSION

2. Design a class according to the UML class diagram shown below:

Rectangle

-length: double

-width: double

+Rectangle()

+Rectangle(len:double, wid:double)

+getArea(): double

+getPerimeter(): double
+drawRect(): void

Where:

- the default constructor (without any parameters) set the length and width

of the rectangle both to be 10.0

- the constructor with parameters will set the length and width of that

rectangle with the given value (if the given value are larger than 0,

otherwise set both to be 10.0)

- getArea() returns the area of that rectangle if the range of the length and

width are between 10 to 50 (inclusive), otherwise return value -1

- getPerimeter() returns the perimeter of the rectangle

- drawRect() draws a shape of that rectangle using asterisk (*) with the

length and width change to integer if the length and width are between

10~50 (inclusive), otherwise draw a shape of 10*10

Write a program (another class) called TestRectangle with the main() to test all

methods within class Rectangle.

 SOURCE CODE (TEXT)

 EXECUTION RESULTS (TEXT OR SNAPSHOTS)

 DISCUSSION AND CONCLUSION

3. Write a program. In which,

Define a class called Vehicle, with


Properties:

- speed, size, brand, and so on (whatever you think is needed);

Methods:

- Constructor method – initiate the variables with given value (from

parameters)

- move() – print a string with current speed, eg. “The vehicle is running

with speed xxx”,

- setSpeed(int speed) – reset the speed to specific value,

- speedup() – increase the speed with 5,

- speedDown() – decrease the speed with 5,

- getSpeed() – return the speed,

- The main method – by instantiating an object of a vehicle, use the

Constructor methods to initiate the value of speed, size and brand

(and the others if necessary). And print the speed of the vehicle object.

Use the methods to reset and change the speed, and then print the

information.

 SOURCE CODE (TEXT)

 EXECUTION RESULTS (TEXT OR SNAPSHOTS)

 DISCUSSION AND CONCLUSION


4. On some phone keypads, the alphabets are mapped to digits as follows:

ABC(2), DEF(3), GHI(4), JKL(5), MNO(6), PQRS(7), TUV(8), WXYZ(9). Write a

program called PhoneKeyPad, which prompts user to input a string (case

insensitive), and converts to a sequence of digits (numbers).

Hints: You can use [Link]().toLowerCase() to read a string and

convert all characters to lowercase (where input is an object of the Scanner

class) to reduce your cases (in switch-case statements); charAt(index) is a

method from String class that you can invoke with an string object to get the

character from certain index, e.g.


String str = “hello”; //index starts from 0, ends at
[Link]()
char ch = [Link](1); //character ‘e’ stores in variable ch

 SOURCE CODE (TEXT)

 EXECUTION RESULTS (TEXT OR SNAPSHOTS)

 DISCUSSION AND CONCLUSION

5. (Algebra: quadratic equations) Design a class named QuadraticEquation for


a quadratic equation ax2 + bx + c = 0. The class contains:
■ Private data fields a, b, and c that represent three coefficients.
■ A constructor for the arguments for a, b, and c.
■ Three getter methods for a, b, and c.
■ A method named getDiscriminant() that returns the discriminant, which is
b2 - 4ac.
■ The methods named getRoot1() and getRoot2() for returning two roots of
the equation

These methods are useful only if the discriminant is nonnegative. Let these
methods return 0 if the discriminant is negative.
Draw the UML diagram for the class and then implement the class. Write a
test
program that prompts the user to enter values for a, b, and c and displays the
result based on the discriminant. If the discriminant is positive, display the two
roots. If the discriminant is 0, display the one root. Otherwise, display “The
equation has no roots.”

 SOURCE CODE (TEXT)

 EXECUTION RESULTS (TEXT OR SNAPSHOTS)

 DISCUSSION AND CONCLUSION

Common questions

Powered by AI

The GregorianCalendar class in Java, found in the java.util package, allows the representation and manipulation of dates. It provides methods such as get(GregorianCalendar.YEAR), get(GregorianCalendar.MONTH), and get(GregorianCalendar.DAY_OF_MONTH) to return the current year, month, and day. The class also has a no-argument constructor that creates an instance representing the current date. Furthermore, the setTimeInMillis(long millis) method allows setting a specific date by specifying milliseconds since January 1, 1970, enabling precise date manipulation .

When constructing the Rectangle class according to the given UML diagram, several design considerations must be made. These include ensuring constructors initialize length and width correctly, where the parameterized constructor sets these to given values greater than 0; otherwise, defaults to 10.0. The methods getArea() and getPerimeter() must accurately calculate the rectangle's area and perimeter, with getArea() returning -1 for lengths and widths outside 10 to 50. DrawRect() requires converting dimensions to integers if within 10 to 50 or resorting to a default shape otherwise. Ensuring these criteria within the class promotes robustness and adherence to the specified requirements .

The getArea() method of the Rectangle class returns a value of -1 when the dimensions—length and width—are outside the specified range between 10 and 50 inclusive. This behavior is significant because it enforces a constraint on valid rectangle dimensions, thereby managing expectations on usable inputs for area calculations. By returning -1 for dimensions outside this range, the method signals an error or invalid condition, which can be crucial for robust error handling and data validation in applications relying on specific geometric constraints .

The getDiscriminant() method directly influences the execution of getRoot1() and getRoot2() in the QuadraticEquation class by determining whether these methods return valid roots of the equation. If the discriminant, calculated as b² - 4ac, is non-negative, it indicates that the quadratic equation has real roots, and getRoot1() and getRoot2() proceed to compute and return these roots. If the discriminant is negative, both methods return 0, reflecting the absence of real roots. This linkage ensures roots are handled appropriately, based on mathematically valid conditions .

Implementing and utilizing the QuadraticEquation class involves several steps. First, define private data fields for the coefficients a, b, and c, and provide a constructor for initializing these fields. Implement getter methods for each coefficient. The getDiscriminant() method should calculate the discriminant (b² - 4ac). Depending on the discriminant's value, methods getRoot1() and getRoot2() should compute and return the quadratic equation's roots, returning them only if the discriminant is non-negative. Lastly, the main program should prompt the user to input values for a, b, and c, calculate the discriminant, and display roots or a message indicating no roots based on the discriminant's sign .

Using private data fields in the QuadraticEquation class is significant because it enforces encapsulation by restricting direct access to the class's internal state. This practice ensures that the fields a, b, and c can only be modified through controlled interfaces such as constructors and getter methods. Encapsulation contributes to data integrity and security by preventing unauthorized modifications and maintaining class invariants. It also simplifies maintenance as changes to internal implementations can be made without affecting external code interfacing with the class .

The PhoneKeyPad program converts alphabetic input into numeric digits as used on phone keypads by mapping each group of letters to a corresponding number. This is achieved by reading a string input, converting it to lowercase to simplify case handling, and then iterating through each character. A switch-case structure identifies the digit associated with each character group (e.g., ABC to 2, DEF to 3, etc.) and outputs the digit sequence. For example, using input.next().toLowerCase() ensures uniformity, while charAt(index) facilitates character extraction for evaluation within the switch-case logic .

The Vehicle class provides core functionalities to manage various vehicle properties, such as speed, size, and brand, through object-oriented principles. It includes a constructor for initializing these properties. Methods like move() print the current speed. Speed management is handled by methods such as setSpeed(int speed) for direct speed adjustment, speedup() for incrementing speed by 5, speedDown() for decrementing speed by 5, and getSpeed() for retrieving the current speed. The main method demonstrates instantiating a vehicle object, initializing properties, and interacting with these methods to modify and display speed dynamics .

Converting alphabetic characters to numeric digits in a program entailing challenges such as handling both uppercase and lowercase inputs, mapping characters to the correct digits, and efficiently processing varying string lengths. The PhoneKeyPad program addresses these challenges by using input.next().toLowerCase() to normalize case differences, enabling a consistent character representation. It employs a switch-case statement to map each character to its corresponding phone keypad digit. This logical structure allows efficient conversion regardless of input length, providing a robust solution to potential mismatches or errors .

Implementing default constructor behaviors in classes like Rectangle is beneficial because it provides a consistent baseline state, ensuring that objects are always initialized with reasonable, pre-determined values even if specific details are not provided by the user. In the Rectangle class, setting default dimensions of 10.0 enhances predictability and prevents uninitialized values that could lead to runtime errors or undefined behavior. This practice aligns with overall software design principles of robustness, reliability, and maintainability, ensuring that class instantiation remains consistent across diverse usage scenarios .

You might also like