JAVA Scenario Programs
JAVA Scenario Programs
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();
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.
PROGRAM:
import java.util.Scanner;
int n = scanner.nextInt();
3
marks[i] = scanner.nextInt();
sum += mark;
int countAboveAverage = 0;
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.");
}
}
}
}
Scenario:
A university library maintains a catalog of book titles. The librarian wants a Java
program that can:
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
Scenario:
A university wants to develop a Student Grade Management System that follows OOP
principles. Your Java program should:
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);
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
18
System.out.println("Exiting Bank System...");
scanner.close();
return;
default:
System.out.println("Invalid Choice! Try Again.");
}
}
}
}
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();
}
}
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: ");
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();
29