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

JAVA Scenario Programs

The document contains multiple Java programming problems, including a scientific calculator, student grade analysis system, student management system, string processing library, student grade management system, and a banking system. Each problem includes a detailed description, input/output requirements, and corresponding Java code implementations. The focus is on utilizing various programming concepts such as data types, arrays, encapsulation, and object-oriented programming principles.

Uploaded by

533manojkumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

JAVA Scenario Programs

The document contains multiple Java programming problems, including a scientific calculator, student grade analysis system, student management system, string processing library, student grade management system, and a banking system. Each problem includes a detailed description, input/output requirements, and corresponding Java code implementations. The focus is on utilizing various programming concepts such as data types, arrays, encapsulation, and object-oriented programming principles.

Uploaded by

533manojkumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

1.

Scientific Computation with Custom Data Type and Operators


Topics Covered: Data Types, Variables, Operators, Control Statements
Problem Statement:
Write a Java program that simulates a scientific calculator. It should:
• Accept user input for two numbers and an operation (+, -, *, /, %, ^).
• Use appropriate data types and handle different precision levels (int, double).
• Implement a menu-driven program using switch-case.
• Handle edge cases (division by zero, negative exponents for integers).
Input:
Enter first number: 5.5
Enter second number: 2
Choose operation: +, -, *, /, %, ^
Enter operation: ^
Output:
Result: 30.25

PROGRAM:
import java.util.Scanner;
public class ScientificCalculator
{
// Method to perform arithmetic operations
public static double calculate(double a, double b, char operator)
{
switch (operator)
{
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/':
if (b == 0)
{
System.out.println("Error: Division by zero is not allowed.");
return Double.NaN;
1
}
return a / b;
case '%': return a % b;
case '^': return Math.pow(a, b);
default:
System.out.println("Invalid operation. Supported operations: +, -, *, /, %, ^");
return Double.NaN;
}
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();

System.out.print("Choose operation (+, -, *, /, %, ^): ");


char operator = scanner.next().charAt(0);

double result = calculate(num1, num2, operator);

if (!Double.isNaN(result))
{
System.out.println("Result: " + result);
}
scanner.close();
}
}

2
2. Problem: Student Grade Analysis System (Using Arrays)

Scenario:
A university wants to analyze students’ marks and calculate statistics such as average,
highest, and lowest marks for a subject.

Write a Java program that:

1. Accepts marks of N students (input from the user).


2. Calculates and prints:
o The average marks.
o The highest and lowest marks.
o The number of students who scored above average.
3. Uses arrays, loops, and control statements efficiently.

PROGRAM:

import java.util.Scanner;

public class StudentGradeAnalysis

public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

// Step 1: Input number of students

System.out.print("Enter number of students: ");

int n = scanner.nextInt();

// Step 2: Declare an array to store marks

int[] marks = new int[n];

// Step 3: Input marks

System.out.println("Enter marks of " + n + " students:");

for (int i = 0; i < n; i++)

System.out.print("Student " + (i + 1) + ": ");

3
marks[i] = scanner.nextInt();

// Step 4: Calculate sum, highest, and lowest marks

int sum = 0, highest = marks[0], lowest = marks[0];

for (int mark : marks)

sum += mark;

if (mark > highest) highest = mark;

if (mark < lowest) lowest = mark;

double average = (double) sum / n; // Calculate average

// Step 5: Count students who scored above average

int countAboveAverage = 0;

for (int mark : marks)

if (mark > average) countAboveAverage++;

} // Step 6: Print results

System.out.println("\n--- Grade Analysis Report ---");

System.out.println("Average Marks: " + average);

System.out.println("Highest Marks: " + highest);

System.out.println("Lowest Marks: " + lowest);

System.out.println("Students Scoring Above Average: " + countAboveAverage);

scanner.close();

4
3. Student Records Management using Arrays and Encapsulation.
Topics Covered: Arrays, Objects & Classes, Encapsulation, Constructors
Problem Statement:
Develop a Student Management System using Java that:
• Maintains student details (ID, Name, GPA) using an array of objects.
• Uses Encapsulation to restrict direct access to attributes.
• Implements constructors for initialization.
Provides methods to:
• Add a student
• Display all students
• Find a student by ID
Input:
1. Add Student
2. Display All
3. Search by ID
4. Exit
Enter choice: 1
Enter ID: 101
Enter Name: Rajesh
Enter GPA: 8.9
Output:
Student Added Successfully!

PROGRAM:
import java.util.Scanner;
// Step 1: Define the Student class with Encapsulation
class Student
{
private int id;
private String name;
private double gpa;
// Constructor to initialize student details
public Student(int id, String name, double gpa)

5
{
this.id = id;
this.name = name;
this.gpa = gpa;
}
// Getter methods to access private attributes
public int getId()
{
return id;
}
public String getName()
{
return name;
}
public double getGpa()
{
return gpa;
}
// Method to display student details
public void displayStudent()
{
System.out.println("ID: " + id + " | Name: " + name + " | GPA: " + gpa);
}
}
// Step 2: Student Management System
public class StudentManagementSystem
{
private static Student[] students = new Student[100]; // Array to store students
private static int studentCount = 0; // Keeps track of the number of students
// Method to add a student
public static void addStudent(int id, String name, double gpa)
{
6
if (studentCount < students.length)
{
students[studentCount++] = new Student(id, name, gpa);
System.out.println("Student added successfully!\n");
}
else
{
System.out.println("Student list is full!");
}
}
// Method to display all students
public static void displayAllStudents()
{
if (studentCount == 0)
{
System.out.println("No students found!");
return;
}
System.out.println("\n--- Student Records ---");
for (int i = 0; i < studentCount; i++)
{
students[i].displayStudent();
}
}
// Method to find a student by ID
public static void findStudentById(int searchId)
{
for (int i = 0; i < studentCount; i++)
{
if (students[i].getId() == searchId)
{
System.out.println("\nStudent Found:");
7
students[i].displayStudent();
return;
}
}
System.out.println("Student with ID " + searchId + " not found!");
}
// Main method to run the program
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
while (true)
{
// Display menu
System.out.println("\n--- Student Management System ---");
System.out.println("1. Add Student");
System.out.println("2. Display All Students");
System.out.println("3. Find Student by ID");
System.out.println("4. Exit");
System.out.print("Choose an option: ");
int choice = scanner.nextInt();
switch (choice)
{
case 1:
System.out.print("\nEnter Student ID: ");
int id = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.print("Enter Student Name: ");
String name = scanner.nextLine();
System.out.print("Enter Student GPA: ");
double gpa = scanner.nextDouble();
addStudent(id, name, gpa);
break;
8
case 2:
displayAllStudents();
break;
case 3:
System.out.print("\nEnter Student ID to Search: ");
int searchId = scanner.nextInt();
findStudentById(searchId);
break;
case 4:
System.out.println("Exiting Student Management System...");
scanner.close();
return;
default:
System.out.println("Invalid choice! Please try again.");
}
}
}
}

4. Problem: String Processing and Manipulation System

Scenario:
A university library maintains a catalog of book titles. The librarian wants a Java
program that can:

1. Accept a book title as input (including spaces).


2. Perform the following operations on the title:
o Convert it to uppercase and lowercase.
o Find the length of the title.
o Count the number of vowels in the title.
o Reverse the title.
3. Use String functions, loops, and methods effectively.

PROGRAM:
import java.util.Scanner;
public class StringProcessingLibrary
{
9
// Method to count vowels in a string
public static int countVowels(String str)
{
int count = 0;
str = str.toLowerCase();
for (char c : str.toCharArray())
{
if ("aeiou".indexOf(c) != -1)
{
count++;
}
}
return count;
}
// Method to reverse a string
public static String reverseString(String str)
{
StringBuilder reversed = new StringBuilder(str);
return reversed.reverse().toString();
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
// Step 1: Input book title
System.out.print("Enter the book title: ");
String bookTitle = scanner.nextLine(); // Read full sentence
// Step 2: Perform operations
System.out.println("\n--- Book Title Analysis ---");
System.out.println("Original Title: " + bookTitle);
System.out.println("Uppercase: " + bookTitle.toUpperCase());
System.out.println("Lowercase: " + bookTitle.toLowerCase());
System.out.println("Length: " + bookTitle.length());
10
System.out.println("Vowel Count: " + countVowels(bookTitle));
System.out.println("Reversed Title: " + reverseString(bookTitle));
scanner.close();
}
}
Output:
Enter the book title: Artificial Intelligence
--- Book Title Analysis ---
Original Title: Artificial Intelligence
Uppercase: ARTIFICIAL INTELLIGENCE
Lowercase: artificial intelligence
Length: 24
Vowel Count: 11
Reversed Title: ecnegilletnI laicifitrA

5. Problem: Student Grade Management System (Encapsulation & OOP)

Scenario:
A university wants to develop a Student Grade Management System that follows OOP
principles. Your Java program should:

1. Define a Student class with private attributes:


o name (String)
o rollNumber (int)
o marks (double)
2. Use encapsulation (private variables + getters & setters).
3. Implement a constructor to initialize student details.
4. Calculate and display the grade based on marks:
o marks >= 90 → Grade A
o marks >= 75 → Grade B
o marks >= 60 → Grade C
o marks >= 50 → Grade D
o marks < 50 → Grade F (Fail)

PROGRAM:
import java.util.Scanner;
class Student
{

11
// Step 1: Private variables (Encapsulation)
private String name;
private int rollNumber;
private double marks;
// Step 2: Constructor
public Student(String name, int rollNumber, double marks)
{
this.name = name;
this.rollNumber = rollNumber;
this.marks = marks;
}
// Step 3: Getter & Setter Methods
public String getName()
{
return name;
}
public int getRollNumber()
{
return rollNumber;
}
public double getMarks()
{
return marks;
}
public void setMarks(double marks)
{
this.marks = marks;
}
// Step 4: Method to Calculate Grade
public String calculateGrade()
{
if (marks >= 90) return "A";
12
else if (marks >= 75) return "B";
else if (marks >= 60) return "C";
else if (marks >= 50) return "D";
else return "F (Fail)";
}
// Step 5: Display Student Information
public void displayStudentInfo()
{
System.out.println("\n--- Student Report ---");
System.out.println("Name: " + name);
System.out.println("Roll Number: " + rollNumber);
System.out.println("Marks: " + marks);
System.out.println("Grade: " + calculateGrade());
}
}
// Step 6: Main Class
public class StudentManagementSystem
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);

// Taking input from user


System.out.print("Enter Student Name: ");
String name = scanner.nextLine();

System.out.print("Enter Roll Number: ");


int rollNumber = scanner.nextInt();

System.out.print("Enter Marks: ");


double marks = scanner.nextDouble();

13
// Creating student object
Student student = new Student(name, rollNumber, marks);
// Displaying student information
student.displayStudentInfo();
scanner.close();
}
}
Output:
Enter Student Name: Alice
Enter Roll Number: 101
Enter Marks: 85
--- Student Report ---
Name: Alice
Roll Number: 101
Marks: 85.0
Grade: B

6. Banking System with Static Members and this Keyword


Topics Covered: Static Members, this Keyword, Methods, Access Specifiers
Problem Statement:
Implement a Bank Account Management System with the following:
• Static member to track the total number of accounts.
• this keyword to differentiate instance variables.
• Access Specifiers to ensure private account details.
• Methods for:
 Deposit
 Withdraw (Check for insufficient balance)
 Show account details
Input:
Create New Account
Enter Name: Priya
Enter Initial Balance: 5000
Output:
Account Created! Total Accounts: 1
14
PROGRAM:
import java.util.Scanner;
// Step 1: Define the BankAccount class with Encapsulation and Static Members
class BankAccount
{
private static int totalAccounts = 0; // Static variable to track accounts
private int accountNumber;
private String accountHolder;
private double balance;
// Constructor to initialize account details using this keyword
public BankAccount(int accountNumber, String accountHolder, double balance)
{
this.accountNumber = accountNumber;
this.accountHolder = accountHolder;
this.balance = balance;
totalAccounts++; // Increment total accounts
}
// Getter methods to access private attributes
public int getAccountNumber()
{
return accountNumber;
}
public String getAccountHolder()
{
return accountHolder;
}
public double getBalance()
{
return balance;
}
// Method to deposit money
public void deposit(double amount)
15
{
if (amount > 0)
{
this.balance += amount;
System.out.println("Deposit Successful! New Balance: $" + this.balance);
}
else
{
System.out.println("Invalid deposit amount!");
}
}
// Method to withdraw money (with insufficient balance check)
public void withdraw(double amount)
{
if (amount > 0 && amount <= this.balance)
{
this.balance -= amount;
System.out.println("Withdrawal Successful! New Balance: $" + this.balance);
}
else
{
System.out.println("Insufficient Balance or Invalid Amount!");
}
}
// Method to display account details
public void displayAccountDetails()
{
System.out.println("\n--- Account Details ---");
System.out.println("Account Number: " + this.accountNumber);
System.out.println("Account Holder: " + this.accountHolder);
System.out.println("Balance: $" + this.balance);
}
16
// Static method to show total number of accounts
public static void showTotalAccounts()
{
System.out.println("\nTotal Bank Accounts: " + totalAccounts);
}
}
// Step 2: Bank Management System
public class BankSystem
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);

// Creating sample bank accounts


BankAccount acc1 = new BankAccount(1001, "Alice", 5000);
BankAccount acc2 = new BankAccount(1002, "Bob", 3000);
// Display initial details
acc1.displayAccountDetails();
acc2.displayAccountDetails();
BankAccount.showTotalAccounts(); // Display total accounts
// Interactive Menu
while (true)
{
System.out.println("\n--- Bank Account Management System ---");
System.out.println("1. Deposit Money");
System.out.println("2. Withdraw Money");
System.out.println("3. Show Account Details");
System.out.println("4. Show Total Accounts");
System.out.println("5. Exit");
System.out.print("Choose an option: ");
int choice = scanner.nextInt();
switch (choice)
17
{
case 1:
System.out.print("\nEnter Account Number: ");
int accNum = scanner.nextInt();
System.out.print("Enter Deposit Amount: ");
double depositAmount = scanner.nextDouble();
if (accNum == acc1.getAccountNumber()) acc1.deposit(depositAmount);
else if (accNum == acc2.getAccountNumber()) acc2.deposit(depositAmount);
else System.out.println("Account Not Found!");
break;
case 2:
System.out.print("\nEnter Account Number: ");
int accNumWithdraw = scanner.nextInt();
System.out.print("Enter Withdrawal Amount: ");
double withdrawAmount = scanner.nextDouble();
if (accNumWithdraw == acc1.getAccountNumber())
acc1.withdraw(withdrawAmount);
else if (accNumWithdraw == acc2.getAccountNumber())
acc2.withdraw(withdrawAmount);
else System.out.println("Account Not Found!");
break;
case 3:
System.out.print("\nEnter Account Number: ");
int accNumDisplay = scanner.nextInt();
if (accNumDisplay == acc1.getAccountNumber()) acc1.displayAccountDetails();
else if (accNumDisplay == acc2.getAccountNumber()) acc2.displayAccountDetails();
else System.out.println("Account Not Found!");
break;
case 4:
BankAccount.showTotalAccounts();
break;
case 5:

18
System.out.println("Exiting Bank System...");
scanner.close();
return;
default:
System.out.println("Invalid Choice! Try Again.");
}
}
}
}

7. Employee Salary Computation with String Functions and Control Statements


Topics Covered: Strings, Control Statements, Methods
Problem Statement:
Create a Payroll System that:
• Takes employee name, designation, and basic salary as input.
• Uses String functions to ensure proper formatting (e.g., capitalize names).
• Uses if-else statements to determine the bonus:
 Manager: 25% of salary
 Developer: 15% of salary
 Intern: 5% of salary
• Computes total salary and displays the formatted output.

Input:
Enter Employee Name: arun
Enter Designation (Manager/Developer/Intern): developer
Enter Basic Salary: 50000

Output:
Employee: Arun
Designation: Developer
Total Salary: 57,500

19
PROGRAM:
import java.util.Scanner;
class Employee
{
private String name;
private String designation;
private double basicSalary;
private double bonus;
// Constructor to initialize employee details
public Employee(String name, String designation, double basicSalary)
{
this.name = formatName(name);
this.designation = designation.toLowerCase(); // Normalize input
this.basicSalary = basicSalary;
this.bonus = calculateBonus();
}
// Method to format the name (capitalize first letter of each word)
private String formatName(String name)
{
String[] words = name.trim().toLowerCase().split("\\s+");
StringBuilder formattedName = new StringBuilder();
for (String word : words)
{
formattedName.append(Character.toUpperCase(word.charAt(0))).append(word.substring(1)).append(" ");

}
return formattedName.toString().trim();
}
// Method to calculate bonus based on designation
private double calculateBonus()
{
if (designation.equals("manager"))
{
20
return 0.25 * basicSalary; // 25% bonus
}
else if (designation.equals("developer"))
{
return 0.15 * basicSalary; // 15% bonus
}
else if (designation.equals("intern"))
{
return 0.05 * basicSalary; // 5% bonus
}
else
{
return 0.0; // No bonus for unrecognized roles
}
}
// Method to calculate total salary
public double getTotalSalary()
{
return basicSalary + bonus;
}
// Method to display employee salary details
public void displaySalaryDetails()
{
System.out.println("\n--- Payroll Details ---");
System.out.println("Employee Name: " + name);
System.out.println("Designation: " + Character.toUpperCase(designation.charAt(0)) +
designation.substring(1));
System.out.println("Basic Salary: $" + basicSalary);
System.out.println("Bonus: $" + bonus);
System.out.println("Total Salary: $" + getTotalSalary());
}
}

21
public class PayrollSystem
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
// Taking user input
System.out.print("Enter Employee Name: ");
String name = scanner.nextLine();
System.out.print("Enter Designation (Manager/Developer/Intern): ");
String designation = scanner.nextLine();
System.out.print("Enter Basic Salary: ");
double basicSalary = scanner.nextDouble();
// Creating Employee object
Employee emp = new Employee(name, designation, basicSalary);
// Display Payroll Details
emp.displaySalaryDetails();
scanner.close();
}
}

8. Hospital Management System using Multi-Dimensional Arrays and


Encapsulation
Topics Covered: Arrays, Objects & Classes, Encapsulation, Constructors
Problem Statement:
Develop a Hospital Patient Management System that:
• Uses a 2D Array to store patient details (Name, Age, Disease).
• Implements Encapsulation to restrict direct data access.
• Includes methods for:
 Admit a new patient
 Display all patients
 Search by disease

22
Input:
1. Admit Patient
2. Display All
3. Search by Disease
4. Exit
Enter choice: 1
Enter Name: Anjali
Enter Age: 35
Enter Disease: Flu
Output:
Patient Admitted Successfully!

PROGRAM:
import java.util.Scanner;
class Hospital
{
private String[][] patients; // 2D array to store patient details
private int capacity;
private int count;
// Constructor to initialize hospital with a maximum number of patients
public Hospital(int capacity)
{
this.capacity = capacity;
this.count = 0;
this.patients = new String[capacity][3]; // 3 columns: Name, Age, Disease
}
// Method to admit a new patient
public void admitPatient(String name, int age, String disease)
{
if (count < capacity)
{
patients[count][0] = name;
patients[count][1] = String.valueOf(age);
23
patients[count][2] = disease;
count++;
System.out.println("Patient admitted successfully!");
}
else
{
System.out.println("Hospital is at full capacity! Cannot admit more patients.");
}
}
// Method to display all patients
public void displayPatients()
{
if (count == 0)
{
System.out.println("No patients admitted yet.");
return;
}
System.out.println("\n--- Hospital Patient Records ---");
System.out.printf("%-20s %-5s %-20s%n", "Name", "Age", "Disease");
System.out.println("------------------------------------------");
for (int i = 0; i < count; i++)
{
System.out.printf("%-20s %-5s %-20s%n", patients[i][0], patients[i][1], patients[i][2]);
}
}
// Method to search for patients by disease
public void searchByDisease(String disease)
{
boolean found = false;
System.out.println("\n--- Patients with " + disease + " ---");
for (int i = 0; i < count; i++)
{
24
if (patients[i][2].equalsIgnoreCase(disease))
{
System.out.printf("Name: %s, Age: %s%n", patients[i][0], patients[i][1]);
found = true;
}
}
if (!found)
{
System.out.println("No patients found with the disease: " + disease);
}
}
}
public class HospitalManagement
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
Hospital hospital = new Hospital(10); // Max 10 patients for this example
while (true)
{
System.out.println("\n--- Hospital Patient Management System ---");
System.out.println("1. Admit New Patient");
System.out.println("2. Display All Patients");
System.out.println("3. Search Patient by Disease");
System.out.println("4. Exit");
System.out.print("Choose an option: ");

int choice = scanner.nextInt();


scanner.nextLine(); // Consume the newline
switch (choice)
{
case 1:
25
System.out.print("Enter Patient Name: ");
String name = scanner.nextLine();
System.out.print("Enter Age: ");
int age = scanner.nextInt();
scanner.nextLine(); // Consume the newline
System.out.print("Enter Disease: ");
String disease = scanner.nextLine();
hospital.admitPatient(name, age, disease);
break;
case 2:
hospital.displayPatients();
break;
case 3:
System.out.print("Enter Disease to Search: ");
String searchDisease = scanner.nextLine();
hospital.searchByDisease(searchDisease);
break;
case 4:
System.out.println("Exiting... Thank you!");
scanner.close();
return;
default:
System.out.println("Invalid choice! Please try again.");
}
}
}
}

26
9. Problem: Employee Salary Management System (this Keyword & Multiple
Constructors)
Scenario:
A company wants to develop an Employee Salary Management System using OOP concepts. The
program should:
1. Define an Employee class with attributes:
• name (String)
• employeeId (int)
• basicSalary (double)
• bonus (double, default is 5000)
2. Use the this keyword to differentiate between instance and local variables.
3. Implement multiple constructors:
• One constructor takes all four parameters (name, employeeId, basicSalary, bonus).
• Another constructor takes three parameters (name, employeeId, basicSalary) and
assigns a default bonus of 5000.
4. Create a method to calculate net salary:
• netSalary = basicSalary + bonus - tax
• Tax: 10% of basic salary
5. Display employee details using a method.

PROGRAM:
import java.util.Scanner;
class Employee
{
// Step 1: Private variables
private String name;
private int employeeId;
private double basicSalary;
private double bonus;
// Step 2: Constructor with all four parameters
public Employee(String name, int employeeId, double basicSalary, double bonus)
{
this.name = name; // Using `this` keyword to differentiate instance and local variable
this.employeeId = employeeId;
this.basicSalary = basicSalary;
this.bonus = bonus;
}
// Step 3: Constructor with three parameters, default bonus = 5000
27
public Employee(String name, int employeeId, double basicSalary)
{
this(name, employeeId, basicSalary, 5000); // Calling another constructor using `this`
}
// Step 4: Method to calculate net salary
public double calculateNetSalary()
{
double tax = 0.10 * basicSalary; // 10% tax deduction
return (basicSalary + bonus - tax);
}
// Step 5: Display Employee Details
public void displayEmployeeInfo()
{
System.out.println("\n--- Employee Salary Details ---");
System.out.println("Name: " + name);
System.out.println("Employee ID: " + employeeId);
System.out.println("Basic Salary: " + basicSalary);
System.out.println("Bonus: " + bonus);
System.out.println("Net Salary: " + calculateNetSalary());
}
}
// Step 6: Main Class
public class EmployeeSalarySystem
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
// Taking input from user
System.out.print("Enter Employee Name: ");
String name = scanner.nextLine();
System.out.print("Enter Employee ID: ");
int employeeId = scanner.nextInt();
28
System.out.print("Enter Basic Salary: ");
double basicSalary = scanner.nextDouble();

System.out.print("Enter Bonus (or enter -1 to use default bonus): ");


double bonus = scanner.nextDouble();
Employee employee;
// Checking if the user entered a custom bonus
if (bonus == -1)
{
employee = new Employee(name, employeeId, basicSalary); // Calls constructor with
default bonus
}
else
{
employee = new Employee(name, employeeId, basicSalary, bonus);
}
// Displaying employee details
employee.displayEmployeeInfo();
scanner.close();
}
}
Output:
Enter Employee Name: John Doe
Enter Employee ID: 2025
Enter Basic Salary: 60000
Enter Bonus (or enter -1 to use default bonus): -1
--- Employee Salary Details ---
Name: John Doe
Employee ID: 2025
Basic Salary: 60000.0
Bonus: 5000.0
Net Salary: 59000.0

29

You might also like