Written by Anonymous
import java.util.ArrayList;
import java.util.Scanner;
public class EncapsulationDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Student> studentList = new ArrayList<>();
int choice;
do {
System.out.println("\n===== MENU =====");
System.out.println("1. Add Student");
System.out.println("2. Update Student");
System.out.println("3. Delete Student");
System.out.println("4. Show All Students");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
choice = sc.nextInt();
sc.nextLine(); // clear buffer
switch (choice) {
case 1:
System.out.print("Enter Name: ");
String name = sc.nextLine();
System.out.print("Enter Age: ");
int age = sc.nextInt();
System.out.print("Enter CGPA: ");
double cgpa = sc.nextDouble();
Student s = new Student(name, age, cgpa);
studentList.add(s);
System.out.println("Student Added Successfully!");
break;
case 2:
System.out.print("Enter index to update: ");
int updateIndex = sc.nextInt();
sc.nextLine();
if (updateIndex >= 0 && updateIndex < studentList.size()) {
System.out.print("Enter New Name: ");
String newName = sc.nextLine();
System.out.print("Enter New Age: ");
int newAge = sc.nextInt();
System.out.print("Enter New CGPA: ");
double newCgpa = sc.nextDouble();
studentList.get(updateIndex).setName(newName);
studentList.get(updateIndex).setAge(newAge);
studentList.get(updateIndex).setCgpa(newCgpa);
System.out.println("Student Updated Successfully!");
} else {
System.out.println("Invalid Index!");
}
break;
case 3:
System.out.print("Enter index to delete: ");
int deleteIndex = sc.nextInt();
if (deleteIndex >= 0 && deleteIndex < studentList.size()) {
studentList.remove(deleteIndex);
System.out.println("Student Deleted Successfully!");
} else {
System.out.println("Invalid Index!");
}
break;
case 4:
if (studentList.isEmpty()) {
System.out.println("No Students Found!");
} else {
for (int i = 0; i < studentList.size(); i++) {
System.out.print("Index " + i + " -> ");
studentList.get(i).display();
}
}
break;
case 5:
System.out.println("Exiting Program...");
break;
default:
System.out.println("Invalid Choice!");
}
} while (choice != 5);
sc.close();
}
}