SUBJECT
Enterprise Java
TOPIC
1. Unit Conversion Program
2. Java Mortgage Calculator
3. Number Guessing Game
Class: TY -BSC(IT) Year: 2024-25
This is to certify that the work entered in this report is the work of Shri / Kumari
HAREESH SURESH CHAUHAN of division ___B___ Roll No. __133__ Uni. Exam No.
_________ has satisfactorily completed and worked for Sem V of the year 2024-25 in the college
laboratory.
Prof. Aarti Patkar
Internal Examiner Internal Examiner Signature
Date: 28/8/ 2024 Department of : INFORMATION TECHNOLOGY
1. Unit Conversion Program
Introduction
The UnitConverter program is a command-line tool designed to convert various units of
measurement across three categories: length, weight, and temperature. It allows users to perform
conversions between commonly used units such as inches to centimeters, pounds to kilograms,
and Celsius to Fahrenheit. The program is designed to run continuously until the user decides to
exit, making it an interactive and user-friendly tool for quick unit conversions.
This program is an excellent example of how fundamental programming concepts like loops,
conditionals, and method calls can be applied to create a practical application. It demonstrates
the importance of user input handling and modularity in software design, making it both an
educational and functional piece of software.
Flowchart
Algorithm
Step 1: Start the program.
The program begins execution, initializing necessary variables and setting up the user interface.
Step 2: Display the main menu.
The program presents the user with the main menu, which includes the available categories
(Length, Weight, and Temperature) and an option to exit.
Step 3: Prompt the user to choose a category.
The program asks the user to select a category by entering the corresponding number (1 for
Length, 2 for Weight, 3 for Temperature, 4 to Exit).
Step 4: Validate the user's choice.
The program checks if the user's input is a valid choice (1, 2, 3, or 4). If the choice is invalid, the
program displays an error message and returns to Step 2.
Step 5: Handle the user's choice.
Based on the user's valid choice, the program branches to the corresponding category-specific
conversion function:
- If the user chooses Length (1), the program calls the convertLength function.
- If the user chooses Weight (2), the program calls the convertWeight function.
- If the user chooses Temperature (3), the program calls the convertTemperature function.
- If the user chooses Exit (4), the program proceeds to Step 10.
Step 6: Display the conversion menu for the selected category.
The program presents the user with the conversion menu for the chosen category, listing the
available conversions.
Step 7: Prompt the user to choose a conversion.
The program asks the user to select a conversion by entering the corresponding number.
Step 8: Validate the user's choice.
The program checks if the user's input is a valid choice for the selected category. If the choice is
invalid, the program displays an error message and returns to Step 6.
Step 9: Perform the conversion.
The program prompts the user to enter the value to be converted, performs the necessary
calculations based on the selected conversion, and displays the result.
Step 10: Check if the user wants to exit.
If the user chose Exit (4) in Step 5, the program proceeds to Step 11. Otherwise, the program
returns to Step 2 to allow the user to perform another conversion.
Step 11: Exit
The program displays a farewell message and terminates execution.
Step Explanation
1. User Interface Loop: The program continuously displays a menu for the user to choose a
conversion category or exit the program.
2. Category Selection: Based on the user’s input, the program directs them to the appropriate
conversion method (length, weight, or temperature).
3. Conversion Methods: Each conversion category (length, weight, temperature) has its method,
which provides further options for specific unit conversions.
4. Input and Calculation: The user inputs a value to convert, and the program performs the
calculation using predefined formulas.
5. Display Results: The program displays the converted value and then returns to the main menu
unless the user decides to exit.
Logic
The core logic of the UnitConverter program is centered around conditional statements and
loops. The main loop repeatedly displays a menu and processes user input to navigate between
different conversion categories. Within each category, specific formulas are applied to convert
the user-inputted values from one unit to another. The use of separate methods for each
conversion category enhances the program's readability and maintainability, allowing for easy
updates or expansions.
Terminology
1. Scanner: A class used to read user input from the console.
2. Method: A block of code that performs a specific task; in this program, methods handle the
different types of conversions.
3. Loop: A programming construct that repeats a block of code as long as a certain condition is
met.
4. Conditional Statements: Used to perform different actions based on different conditions (e.g.,
if, switch).
5. Conversion Formula: Mathematical equations used to convert values from one unit to another
(e.g., inches to centimeters).
Running module
To run the UnitConverter program:
1. Compile the Code: Ensure that the Java Development Kit (JDK) is installed. Save the code in
a file named [Link] and compile it using the command:
javac [Link]
2. Run the Program: After successful compilation, run the program with the command:
java UnitConverter
3. Interact with the Program: The program will display a menu where you can choose a
conversion category. Follow the prompts to input values and see the converted results.
4. Exit the Program: Choose the "Exit" option from the main menu when you are done.
The UnitConverter will handle invalid inputs gracefully and will prompt the user to try again if
an invalid selection is made.
Code
import [Link];
public class UnitConverter {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
boolean running = true;
while (running) {
[Link]("\n--- Unit Converter ---");
[Link]("1. Length");
[Link]("2. Weight");
[Link]("3. Temperature");
[Link]("4. Exit");
[Link]("\nChoose a category: ");
int choice = [Link]();
[Link]();
switch (choice) {
case 1:
convertLength(scanner);
break;
case 2:
convertWeight(scanner);
break;
case 3:
convertTemperature(scanner);
break;
case 4:
[Link]("\nExiting...");
running = false;
break;
default:
[Link]("\nInvalid choice. Please try again.");
break;
}
}
}
private static void convertLength(Scanner scanner) {
[Link]("\n--- Length Conversion ---");
[Link]("1. Inches to Centimeters");
[Link]("2. Feet to Meters");
[Link]("3. Miles to Kilometers");
[Link]("\nChoose a conversion: ");
int choice = [Link]();
[Link]();
[Link]("\nEnter the value: ");
double value = [Link]();
switch (choice) {
case 1:
double cmValue = value * 2.54;
[Link]("\n" + value + " inches = " + cmValue + " centimeters");
break;
case 2:
double mValue = value * 0.3048;
[Link]("\n" + value + " feet = " + mValue + " meters");
break;
case 3:
double kmValue = value * 1.609;
[Link]("\n" + value + " miles = " + kmValue + " kilometers");
break;
default:
[Link]("\nInvalid choice. Please try again.");
break;
}
}
private static void convertWeight(Scanner scanner) {
[Link]("\n--- Weight Conversion ---");
[Link]("1. Ounces to Grams");
[Link]("2. Pounds to Kilograms");
[Link]("3. Stones to Kilograms");
[Link]("\nChoose a conversion: ");
int choice = [Link]();
[Link]();
[Link]("\nEnter the value: ");
double value = [Link]();
switch (choice) {
case 1:
double gValue = value * 28.3495;
[Link]("\n" + value + " ounces = " + gValue + " grams");
break;
case 2:
double kgValue = value * 0.453592;
[Link]("\n" + value + " pounds = " + kgValue + " kilograms");
break;
case 3:
double stoneValue = value * 6.35029;
[Link]("\n" + value + " stones = " + stoneValue + " kilograms");
break;
default:
[Link]("\nInvalid choice. Please try again.");
break;
}
}
private static void convertTemperature(Scanner scanner) {
[Link]("\n--- Temperature Conversion ---");
[Link]("1. Celsius to Fahrenheit");
[Link]("2. Fahrenheit to Celsius");
[Link]("\nChoose a conversion: ");
int choice = [Link]();
[Link](); // Consume newline character
[Link]("\nEnter the value: ");
double value = [Link]();
switch (choice) {
case 1:
double fValue = (value * 9 / 5) + 32;
[Link]("\n" + value + " degrees Celsius = " + fValue + " degrees
Fahrenheit");
break;
case 2:
double cValue = (value - 32) * 5 / 9;
[Link]("\n" + value + " degrees Fahrenheit = " + cValue + " degrees
Celsius");
break;
default:
[Link]("\nInvalid choice. Please try again.");
break;
}
}
}
Output
2. Java Mortgage Calculator
Introduction
The Mortgage Calculator program is a command-line application designed to assist users in
calculating their monthly mortgage payments based on the loan amount (principal), annual
interest rate, and loan term in years. By entering these values, the program will compute the
monthly mortgage payment using a standard mortgage formula. Additionally, it provides
information on the total amount to be paid over the loan period and the total interest incurred,
offering a comprehensive overview of the financial obligations associated with the mortgage.
This calculator is a practical tool for individuals considering taking out a mortgage or those who
wish to understand how different loan terms and interest rates affect their monthly payments. It
serves as a valuable resource for financial planning, enabling users to make informed decisions
about their mortgage options.
Flowchart
Algorithm
Step 1: Input Parameters
- Principal amount (P)
- Annual interest rate (A)
- Loan period in years (Y)
Step 2: Calculate Monthly Interest Rate
- Monthly interest rate (MIR) = A / 100 / 12
Step 3: Calculate Number of Payments
- Number of payments (N) = Y * 12
Step 4: Calculate Monthly Mortgage Payment
- Monthly mortgage payment (M) = P * (MIR * (1 + MIR)^N) / ((1 + MIR)^N - 1)
Step 5: Format and Display Result
- Format M to two decimal places
- Display "Mortgage: " + formatted M
Step 6: Exit
- End program
This algorithm outlines the step-by-step process for calculating the monthly mortgage payment
based on the input parameters.
Step Explanation
1. User Input: The program begins by prompting the user to input the loan amount (principal),
the annual interest rate, and the loan term in years.
2. Convert Rates and Terms: The annual interest rate is converted to a monthly interest rate, and
the loan term in years is converted to the total number of monthly payments.
3. Mortgage Calculation: The program calculates the monthly mortgage payment using the
mortgage payment formula, which accounts for the principal, monthly interest rate, and number
of payments.
4. Output Results: The calculated monthly payment is displayed, along with the total payment
over the loan term and the total interest paid.
5. Program Termination: After displaying the results, the program closes, ending the session.
Logic
The logic behind the MortgageCalculator program involves basic financial calculations,
specifically the use of the mortgage payment formula. This formula is a standard in finance for
determining the fixed monthly payment required to pay off a loan over a specified period at a
fixed interest rate. By breaking down the annual interest rate into a monthly rate and converting
the loan term into the total number of monthly payments, the program can accurately calculate
the fixed monthly payment. Additionally, it calculates the total cost of the loan and the total
interest, giving users a complete financial picture.
Terminology
1. Principal: The original loan amount or the amount borrowed that needs to be repaid.
2. Interest Rate: The percentage charged on the loan, expressed annually but converted to a
monthly rate for calculations.
3. Loan Term: The duration over which the loan will be repaid, typically expressed in years.
4. Monthly Payment: The fixed amount paid every month to cover the loan, including both
principal and interest.
5. Total Payment: The total amount paid over the entire loan term, including both principal and
interest.
6. Total Interest: The amount paid in interest over the life of the loan, which is the difference
between the total payment and the principal.
Code
import [Link];
import [Link];
public class MortgageCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
DecimalFormat df = new DecimalFormat("#.##");
[Link]("Welcome to the Mortgage Calculator!");
[Link]("Loan Amount (principal): ");
double principal = [Link]();
[Link]("Annual interest rate (percentage): ");
double annualInterestRate = [Link]();
[Link]("Loan term (years): ");
int years = [Link]();
double monthlyInterestRate = annualInterestRate / 100 / 12;
int numberOfPayments = years * 12;
double monthlyPayment = (principal * monthlyInterestRate * [Link](1 +
monthlyInterestRate, numberOfPayments))
/ ([Link](1 + monthlyInterestRate, numberOfPayments) - 1);
[Link]("Monthly payment is: " + [Link](monthlyPayment));
double totalPayment = monthlyPayment * numberOfPayments;
double totalInterest = totalPayment - principal;
[Link]("Total payment of the loan: " + [Link](totalPayment));
[Link]("Total interest of the loan: " + [Link](totalInterest));
[Link]();
}
}
Output
3. Number Guessing Game
Introduction
The NumberGuessingGame is a simple interactive console-based game that challenges players to
guess a randomly generated number within a specified range. The game selects a random number
between a predefined lower and upper bound, typically between 1 and 100. The player must then
attempt to guess this number by inputting their guesses. After each guess, the game provides
feedback, informing the player whether their guess is too low, too high, or correct. The game
continues until the player correctly identifies the number, making it a fun way to engage in
logical deduction and probability.
This game not only offers entertainment but also serves as an excellent introduction to basic
programming concepts such as loops, conditionals, input/output handling, and random number
generation. By playing or implementing this game, users can better understand how computers
process user input and provide real-time feedback. The NumberGuessingGame is a foundational
exercise often used in introductory programming courses to reinforce understanding of control
flow and algorithmic thinking.
Algorithm
Step 1: Initialization
- Define the range for the random number (lowerBound and upperBound)
- Generate a random number (numberToGuess) within the defined range
- Initialize the number of tries (numberOfTries) to 0
- Initialize a flag (hasGuessedCorrectly) to false
Step 2: User Input
- Prompt the user to enter their guess
- Read the user's input (playerGuess)
Step 3: Input Validation
- Check if the user's guess is within the defined range
- If not, display an error message and repeat Step 2
Step 4: Comparison
- Compare the user's guess to the random number (numberToGuess)
- If the guess is less than the random number, display "Too low! Try again."
- If the guess is greater than the random number, display "Too high! Try again."
- If the guess is equal to the random number, set hasGuessedCorrectly to true
Step 5: Update and Repeat
- Increment the number of tries (numberOfTries)
- If hasGuessedCorrectly is false, repeat Steps 2-5
- If hasGuessedCorrectly is true, proceed to Step 6
Step 6: Game Over
- Display a congratulatory message with the correct number and number of tries
- End the game
This algorithm outlines the step-by-step process for the Number Guessing Game, ensuring a fun
and interactive experience for the user.
Flowchart
Step Explanation
1. Initialize Scanner and Random:
- The Scanner is used to capture user input, and Random is used to generate a random number.
2. Define Range:
- The range for the random number is defined by lowerBound and upperBound.
3. Generate Random Number:
- The [Link]() method is used to generate a random number between lowerBound and
upperBound.
4. Initialize Counters and Flags:
- numberOfTries counts the number of guesses the user makes.
- hasGuessedCorrectly is a boolean flag that tracks whether the user has guessed the correct
number.
5. Display Welcome Message:
- A message is printed to the console to welcome the player and inform them of the range.
6. Main Game Loop:
- The loop continues until the user guesses the correct number (hasGuessedCorrectly becomes
true).
- The user is prompted to enter their guess.
- The program checks if the guess is within the defined range.
- Depending on the comparison between the guess and the generated number, feedback is
provided:
- "Too low!" if the guess is lower.
- "Too high!" if the guess is higher.
- If the guess is correct, the loop is exited, and a congratulatory message is displayed.
7. Close Scanner:
- After the game ends, the Scanner is closed to free system resources.
Logic
The game revolves around the concept of guessing a randomly generated number. The key
logical components include:
Random Number Generation: Ensures that each game has a different number, adding
unpredictability.
Input Validation: Ensures that the user’s guess falls within the defined range.
Comparison Logic: Determines if the guessed number is too high, too low, or correct.
Looping Structure: Repeats the guessing process until the correct number is guessed.
Terminology
Scanner: A class in Java used to take input from the user.
Random: A class in Java used to generate random numbers.
Range: The minimum and maximum values within which the random number is generated.
Loop: A control flow statement that allows code to be executed repeatedly based on a condition.
Condition: A statement that the program evaluates to true or false.
Running module
To run the NumberGuessingGame:
1. Set Up Environment:
- Ensure you have a Java Development Kit (JDK) installed.
- Write the code in a .java file, for example, [Link].
2. Compile the Program:
- Open a terminal or command prompt.
- Navigate to the directory where the .java file is located.
- Compile the program using the command: javac [Link]
3. Run the Program:
- After compilation, run the program using the command: java NumberGuessingGame.
- The program will start, and the user can interact with it by entering their guesses.
4. Gameplay:
- Follow the prompts to guess the number.
- Receive feedback after each guess.
- Continue guessing until the correct number is found.
By following these steps, you can compile and run the Number Guessing Game in any
environment that supports Java.
Code
import [Link];
import [Link];
public class NumberGuessingGame {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
Random random = new Random();
// Define the range for the random number
int lowerBound = 1;
int upperBound = 100;
int numberToGuess = [Link](upperBound - lowerBound + 1) + lowerBound;
int numberOfTries = 0;
boolean hasGuessedCorrectly = false;
[Link]("Welcome to the Number Guessing Game!");
[Link]("I have selected a number between " + lowerBound + " and " +
upperBound + ". Try to guess it!");
while (!hasGuessedCorrectly) {
[Link]("Enter your guess: ");
int playerGuess = [Link]();
numberOfTries++;
if (playerGuess < lowerBound || playerGuess > upperBound) {
[Link]("Please guess a number within the range of " + lowerBound + " to "
+ upperBound + ".");
} else if (playerGuess < numberToGuess) {
[Link]("Too low! Try again.");
} else if (playerGuess > numberToGuess) {
[Link]("Too high! Try again.");
} else {
hasGuessedCorrectly = true;
[Link]("Congratulations! You've guessed the number " + numberToGuess
+ " in " + numberOfTries + " tries.");
}
}
[Link]();
}
}
Output