0% found this document useful (0 votes)
7 views

Java Experiment

Uploaded by

randel.ducusin03
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Java Experiment

Uploaded by

randel.ducusin03
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

NCP 3106 – Software Design Laboratory

Name: CADANO, JOHN CARLO experiment#: 5

Student Number: 20221128081 Activity Title: INTRODUCTION OF CLASSES

Example Program #1
package example1;
import java.util.Scanner; // Needed for the Scanner class
import java.util.Random; // Needed for the Random class
import java.io.*; // Needed for file I/O classes
public class Example1 {
public static void main(String[] args) throws FileNotFoundException {
int maxNumbers; // Max number of random numbers
int number; // To hold a random number
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Create a Random object to generate random numbers.
Random rand = new Random();
// Create a PrintWriter object to open the file.
PrintWriter outputFile = new PrintWriter("numbers.txt");
// Get the number of random numbers to write.
System.out.print("How many random numbers should I write? ");
maxNumbers = keyboard.nextInt();
for (int count = 0; count < maxNumbers; count++) {
// Generate a random integer.
number = rand.nextInt();
// Write the random integer to the file.
outputFile.println(number);
}
// Close the file.
outputFile.close();
System.out.println("Done");
}
}
RESULT

College of Engineering Page 1 of 18


Computer Engineering Department
NCP 3106 – Software Design Laboratory

OBSERVATION:
A user-specified number of random integers is successfully generated by this program and written to a text file
called numbers.txt. The program manages the entire process effectively by using the Random class to generate
random numbers and the Scanner class to process user input. For the majority of typical applications, the
random numbers are limited to the range of 0 to 99. Even in the case of an exception, the try-catch-finally block
guarantees that possible errors, like problems with file creation, are appropriately handled and that resources,
such as the file and scanner, are closed at the end. All things considered, the code exhibits strong resource
management and error handling, making it reliable for file operations.

Example Program #2
package example1;
public class Rectangle {
private double length;
private double width;
/**
The setLength method stores a value in the length field.
@param len The value to store in length.
*/
public void setLength(double len){
length = len;
}
/**
The setWidth method stores a value in the width field.
@param w The value to store in width.
*/
public void setWidth(double w){
width = w;
}
/**
The getLength method returns a Rectangle object's length.
@return The value in the length field.
*/
public double getLength(){
return length;
}
/**
The getWidth method returns a Rectangle object's width.
@return The value in the width field.
College of Engineering Page 2 of 18
Computer Engineering Department
NCP 3106 – Software Design Laboratory
*/
public double getWidth(){
return width;
}
/**
The getArea method returns a Rectangle object's area.
@return The product of length times width.
*/
public double getArea() {
return length * width;
}
}

RESULT

OBSERVATION:
The Rectangle class is a straightforward yet effective representation of a rectangle's properties and behaviors,
designed to handle fundamental operations related to length and width. It provides setter methods for both
dimensions, allowing users to specify the rectangle's size dynamically. This design ensures that the length and
width can be modified as needed, making the class flexible for various applications. The getter methods for
length and width allow easy retrieval of these values, promoting encapsulation by keeping the data fields private
and preventing direct access. Additionally, the class includes a method to calculate the area, which is derived by
multiplying the length and width. This encapsulation of data and methods allows the class to represent a
rectangle comprehensively, making it a valuable tool in programs that require geometric calculations or
graphical representations. Overall, the Rectangle class effectively encapsulates the essential characteristics and
functionalities of rectangles, making it suitable for educational purposes and practical

College of Engineering Page 3 of 18


Computer Engineering Department
NCP 3106 – Software Design Laboratory
Example Program #3
package example1;
public class Example1 {
public static void main(String[] args) {
// Create a Rectangle object.
Rectangle box = new Rectangle();
// Set length to 10.0 and width to 20.0.
box.setLength(10.0);
box.setWidth(20.0);
// Display the length.
System.out.println("The box's length is " + box.getLength());
// Display the width.
System.out.println("The box's width is " + box.getWidth());
// Display the area.
System.out.println("The box's area is " + box.getArea());
}
}

RESULT

OBSERVATION:
In this program, the Experiment class is used to create a Rectangle object called box, and it demonstrates how to
set the object's length and width using setter methods. The program successfully retrieves and prints the box's
dimensions and calculates its area using the getArea method. This demonstrates the fundamental concepts of
object-oriented programming, such as encapsulation and using methods to access and manipulate object
properties. The approach is clear and functional, making it easy to understand how the Rectangle class works in
practice.

Example Program #4
package example1;
import javax.swing.JOptionPane;
public class Example1 {
public static void main(String[] args) {
double number; // To hold a number
College of Engineering Page 4 of 18
Computer Engineering Department
NCP 3106 – Software Design Laboratory
double totalArea; // The total area
String input; // To hold user input
// Create three Rectangle objects.
Rectangle kitchen = new Rectangle();
Rectangle bedroom = new Rectangle();
Rectangle den = new Rectangle();
// Get and store the dimensions of the kitchen.
input = JOptionPane.showInputDialog("What is the kitchen's length?");
number = Double.parseDouble(input);
kitchen.setLength(number);
input = JOptionPane.showInputDialog("What is the kitchen's width?");
number = Double.parseDouble(input);
kitchen.setWidth(number);
// Get and store the dimensions of the bedroom.
input = JOptionPane.showInputDialog("What is the bedroom's length?");
number = Double.parseDouble(input);
bedroom.setLength(number);
input = JOptionPane.showInputDialog("What is the bedroom's width?");
number = Double.parseDouble(input);
bedroom.setWidth(number);
// Get and store the dimensions of the garden.
input = JOptionPane.showInputDialog("What is the garden's length?");
number = Double.parseDouble(input);
den.setLength(number);
input = JOptionPane.showInputDialog("What is the garden's width?");
number = Double.parseDouble(input);
den.setWidth(number);
// Calculate the total area of the rooms.
totalArea = kitchen.getArea() + bedroom.getArea() + den.getArea();
// Display the total area of the rooms.
JOptionPane.showMessageDialog(null, "The total area of the rooms is " + totalArea);
}
}

RESULT

College of Engineering Page 5 of 18


Computer Engineering Department
NCP 3106 – Software Design Laboratory

College of Engineering Page 6 of 18


Computer Engineering Department
NCP 3106 – Software Design Laboratory

OBSERVATION:
In this program, the user is prompted to enter the dimensions (length and width) for three rooms: the kitchen,
bedroom, and garden (referred to as the den in the code). The JOptionPane class is used to gather input through
dialog boxes, converting the string inputs to doubles. The dimensions are stored in three separate Rectangle
objects, and the total area of all three rooms is calculated by summing the areas of each individual room. This
approach effectively demonstrates the use of multiple object instances and how to interact with users for input,
displaying results in a simple GUI. The program is intuitive and applies object-oriented concepts while also
introducing basic user interaction.
Example Program #4
package example1;
public class Rectangle {
private double length;
private double width;
/**
Constructor
@param len The length of the rectangle.
@param w The width of the rectangle.
*/
public Rectangle(double len, double w) {
length = len;
width = w;
}
/**
The setLength method stores a value in the length field.
@param len The value to store in length.
*/
public void setLength(double len){
length = len;
}
/**
The setWidth method stores a value in the width field.
@param w The value to store in width.
*/
public void setWidth(double w){
width = w;
}
/**
The getLength method returns a Rectangle object's length.
College of Engineering Page 7 of 18
Computer Engineering Department
NCP 3106 – Software Design Laboratory
@return The value in the length field.
*/
public double getLength(){
return length;
}
/**
The getWidth method returns a Rectangle object's width.
@return The value in the width field.
*/
public double getWidth(){
return width;
}
/**
The getArea method returns a Rectangle object's area.
@return The product of length times width.
*/
public double getArea() {
return length * width;
}
}
RESULT

College of Engineering Page 8 of 18


Computer Engineering Department
NCP 3106 – Software Design Laboratory

OBSERVATION:

The Rectangle class provides a simple way to model a rectangle's dimensions and calculate its area. It consists
of two fields, length and width, which can be set through either the constructor or mutator methods (setLength
and setWidth). The class includes accessor methods (getLength and getWidth) to retrieve the current values of
the length and width. Additionally, the getArea method calculates the rectangle's area by multiplying its length
and width. This class encapsulates basic functionality to manage rectangle objects while maintaining flexibility
through its mutators and accessors.

Example Program #5
package example1;
public class Example1 {
public static void main(String[] args) {
// Create a Rectangle object, passing 5.0 and
// 15.0 as arguments to the constructor.
College of Engineering Page 9 of 18
Computer Engineering Department
NCP 3106 – Software Design Laboratory
Rectangle box = new Rectangle(5.0, 15.0);
System.out.println("The box's length is " + box.getLength());
System.out.println("The box's width is " + box.getWidth());
System.out.println("The box's area is " + box.getArea());
}
}

RESULT

OBSERVATION:
The Experiment class effectively demonstrates the use of the Rectangle class by creating an instance named
box, initialized with specific dimensions of 5.0 for length and 15.0 for width. This initialization utilizes the
constructor, allowing for direct setting of values upon object creation. The program then retrieves the length and
width of the box through the getLength() and getWidth() methods, which encapsulate the private fields while
maintaining data protection. It calculates the area by invoking the getArea() method, showcasing how the class
handles the logic for computing area without exposing implementation details. The output, displayed through
System.out.println(), provides clear and concise information about the rectangle's properties, making it easy to
verify the length, width, and area. Overall, this program exemplifies good object-oriented programming
practices, highlighting encapsulation and method utilization, thus ensuring the Rectangle class can be reused in
different contexts without altering its core logic.

Example Program #6
package example1;
import java.util.Random;
public class Die {
private int sides; // Number of sides
private int value; // The die's value
/**
The constructor performs an initial roll of the die.
College of Engineering Page 10 of
18
Computer Engineering Department
NCP 3106 – Software Design Laboratory
@param numSides The number of sides for this die.
*/
public Die(int numSides) {
sides = numSides;
roll();
}
/**
The roll method simulates the rolling of the die.
*/
public void roll() {
// Create a Random object.
Random rand = new Random();
// Get a random value for the die.
value = rand.nextInt(sides) + 1;
}
/**
getSides method
@return The number of sides for this die.
*/
public int getSides() {
return sides;
}
/**
getValue method
@return The value of the die.
*/
public int getValue() {
return value;
}
}

RESULT

College of Engineering Page 11 of


18
Computer Engineering Department
NCP 3106 – Software Design Laboratory

OBSERVATION:
The Die class effectively models the behavior of a die in programming, showcasing good practices in object-
oriented design. It encapsulates two key properties: sides, representing the number of sides on the die, and
value, which indicates the current showing value after a roll. The constructor initializes the die with a specified
number of sides and performs an initial roll, ensuring the value is set immediately for immediate use. The roll
method utilizes the Random class to generate a random integer between 1 and the number of sides, effectively
simulating the unpredictability of dice rolls. Furthermore, getter methods such as getSides and getValue provide
access to the die's properties while preventing direct modification, promoting data integrity. This design allows
for potential expansions, such as adding methods for multi-rolls or tracking statistics, making the Die class a
valuable foundation for simulations or game development. Overall, it demonstrates how to create a simple yet
effective representation of a die, making it an essential component in programming contexts that involve
randomness and chance.

Example Program #7
package example1;
public class Example1 {
public static void main(String[] args) {
final int SIX_SIDES = 6;
final int TWENTY_SIDES = 20;
// Create a 6-sided die.
Die sixDie = new Die(SIX_SIDES);
// Create a 20-sided die.
Die twentyDie = new Die(TWENTY_SIDES);
// Roll the dice.
rollDie(sixDie);
rollDie(twentyDie);
}
/**
This method simulates a die roll, displaying the die's number of sides and value.
@param d The Die object to roll.
*/
public static void rollDie(Die d) {
// Display the number of sides.
System.out.println("Rolling a " + d.getSides() + " sided die.");
College of Engineering Page 12 of
18
Computer Engineering Department
NCP 3106 – Software Design Laboratory
// Roll the die.
d.roll();
// Display the die's value.
System.out.println("The die's value: " + d.getValue());
}
}

RESULT

OBSERVATION
In this simulation, the code effectively demonstrates how objects and methods interact to create a simple dice-
rolling game. By encapsulating the behavior of a die in a class, it allows for easy manipulation of dice with
different configurations. Each roll provides immediate feedback about the die's sides and value, making the
program engaging. The randomization aspect ensures that each run of the program yields different results,
enhancing the dynamic nature of the simulation. This structure not only aids in understanding object-oriented
programming principles but also showcases how randomness can be integrated into Java applications for
entertainment purposes.

Example Program #8
package example1;
public class BankAccount {
private double balance; // Account balance
/**
College of Engineering Page 13 of
18
Computer Engineering Department
NCP 3106 – Software Design Laboratory
This constructor sets the starting balance at 0.0.
*/
public BankAccount() {
balance = 0.0;
}
/**
This constructor sets the starting balance to the value passed as an argument.
@param startBalance The starting balance.
*/
public BankAccount(double startBalance) {
balance = startBalance;
}
/**
This constructor sets the starting balance to the value in the String argument.
@param str The starting balance, as a String.
*/
public BankAccount(String str) {
balance = Double.parseDouble(str);
}
/**
The deposit method makes a deposit into the account.
@param amount The amount to add to the balance field.
*/
public void deposit(double amount) {
balance += amount;
}
/**
The deposit method makes a deposit into the account.
@param str The amount to add to the balance field, as a String.
*/
public void deposit(String str) {
balance += Double.parseDouble(str);
}
/**
The withdraw method withdraws an amount from the account.
@param amount The amount to subtract from the balance field.
*/
public void withdraw(double amount) {
balance -= amount;
}
/**
The withdraw method withdraws an amount from the account.
@param str The amount to subtract from the balance field, as a String.
*/

College of Engineering Page 14 of


18
Computer Engineering Department
NCP 3106 – Software Design Laboratory
public void withdraw(String str) {
balance -= Double.parseDouble(str);
}
/**
The setBalance method sets the account balance.
@param b The value to store in the balance field.
*/
public void setBalance(double b) {
balance = b;
}
/**
The setBalance method sets the account balance.
@param str The value, as a String, to store in the balance field.
*/
public void setBalance(String str) {
balance = Double.parseDouble(str);
}
/**
The getBalance method returns the account balance.
@return The value in the balance field.
*/
public double getBalance() {
return balance;
}
}
RESULT

College of Engineering Page 15 of


18
Computer Engineering Department
NCP 3106 – Software Design Laboratory

OBSERVATION:

The BankAccount class serves as a comprehensive representation of a bank account, encapsulating the essential
features and functionalities needed to manage an account's balance. With multiple constructors, it provides
flexibility for initializing an account, whether starting with a zero balance, a specified double value, or a string
representation of the balance. This versatility caters to various use cases, ensuring that users can create accounts
in a manner that best suits their needs. The class also includes methods for depositing and withdrawing funds,
both accepting numeric and string inputs, which enhances usability and user experience. By allowing deposits
and withdrawals through both types of input, the class accommodates different programming contexts, making
it easier to interact with account balances. Additionally, the inclusion of getter and setter methods ensures that
the balance is managed safely, preventing direct modifications while still allowing access to its value. Overall,
the BankAccount class effectively encapsulates the properties and behaviors expected from a banking
application, making it a valuable component for developing more complex financial systems.

Example Program #9
package example1;
import javax.swing.JOptionPane; // For the JOptionPane class
public class Example1 {
public static void main(String[] args) {
String input; // To hold user input
// Get the starting balance.
input = JOptionPane.showInputDialog("What is your account's starting balance?");
// Create a BankAccount object.

College of Engineering Page 16 of


18
Computer Engineering Department
NCP 3106 – Software Design Laboratory
BankAccount account = new BankAccount(input);
// Get the amount of pay.
input = JOptionPane.showInputDialog("How much were you paid this month?");
// Deposit the user's pay into the account.
account.deposit(input);
// Display the new balance.
JOptionPane.showMessageDialog(null, String.format("Your pay has been deposited.\n Your current balance is
$%,.2f", account.getBalance()));
// Withdraw some cash from the account.
input = JOptionPane.showInputDialog("How much would you like to withdraw?");
account.withdraw(input);
// Display the new balance
JOptionPane.showMessageDialog(null, String.format("Now your balance is $%,.2f",account.getBalance()));
System.exit(0);
}
}

RESULT

College of Engineering Page 17 of


18
Computer Engineering Department
NCP 3106 – Software Design Laboratory

OBSERVATION
The Experiment class serves as a practical demonstration of how to manage a bank account using user
interactions via dialog boxes. It begins by prompting the user to input their account's starting balance, which
initializes a BankAccount object. This interactive approach makes it user-friendly, allowing individuals to
easily input financial information. After establishing the starting balance, the program requests the user's
monthly pay, which is then deposited into the account using the deposit method. This operation showcases the
class's functionality while providing immediate feedback through a dialog that displays the updated balance.
Furthermore, the program allows users to withdraw funds by prompting for an amount and then updating the
account balance accordingly. Each step includes informative messages, enhancing user understanding of the
account's status throughout the process. Overall, the Experiment class effectively combines user input, account
management, and output formatting, demonstrating a simple yet robust approach to handling basic banking
operations.

College of Engineering Page 18 of


18
Computer Engineering Department

You might also like