package examportal;

import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Scanner;

public class ExamPortal {

private static final String DB_URL = "jdbc:mysql://localhost:3306/examportal";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "password";

private static Connection conn;
private static PreparedStatement stmt;
private static ResultSet rs;

private static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
    System.out.println("Welcome to Exam Portal!");
    while (true) {
        System.out.println("Please choose your role:");
        System.out.println("1. Student");
        System.out.println("2. Teacher");
        System.out.println("3. Exit");
        int roleChoice = scanner.nextInt();
        scanner.nextLine();
        switch (roleChoice) {
            case 1:
                studentMenu();
                break;
            case 2:
                teacherMenu();
                break;
            case 3:
                System.out.println("Bye!");
                return;
            default:
                System.out.println("Invalid choice!");
        }
    }
}

private static void studentMenu() {
    System.out.println("Please choose your action:");
    System.out.println("1. Register");
    System.out.println("2. Login");
    System.out.println("3. Back");
    int choice = scanner.nextInt();
    scanner.nextLine();
    switch (choice) {
        case 1:
            registerStudent();
            break;
        case 2:
            loginStudent();
            break;
        case 3:
            return;
        default:
            System.out.println("Invalid choice!");
    }
}

private static void registerStudent() {
    System.out.println("Please enter your name:");
    String name = scanner.nextLine();
    System.out.println("Please enter your student ID:");
    String studentId = scanner.nextLine();
    System.out.println("Please enter your password:");
    String password = scanner.nextLine();
    try {
        conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
        stmt = conn.prepareStatement("INSERT INTO students (name, student_id, password) VALUES (?, ?, ?)");
        stmt.setString(1, name);
        stmt.setString(2, studentId);
        stmt.setString(3, password);
        stmt.executeUpdate();
        System.out.println("Registration successful!");
    } catch (SQLException e) {
        System.out.println("Registration failed: " + e.getMessage());
    } finally {
        closeResources();
    }
}

private static void loginStudent() {
    System.out.println("Please enter your student ID:");
    String studentId = scanner.nextLine();
    System.out.println("Please enter your password:");
    String password = scanner.nextLine();
    try {
        conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
        stmt = conn.prepareStatement("SELECT id, name FROM students WHERE student_id = ? AND password = ?");
        stmt.setString(1, studentId);
        stmt.setString(2, password);
        rs = stmt.executeQuery();
        if (rs.next()) {
            int studentIdDb = rs.getInt("id");
            String name = rs.getString("name");
            System.out.println("Welcome, " + name + "!");
            studentExam(studentIdDb);
        } else {
            System.out.println("Login failed: incorrect student ID or password.");
        }
    } catch (SQLException e) {
        System.out.println("Login failed: " + e.getMessage());
    } finally {
        closeResources();
    }
}

private static void studentExam(int studentIdDb) {
    System.out.println("Please choose a course:");
    List<Course> courses = getAvailableCourses();
    for (Course course : courses) {
        System.out.println(course.getName() + " (ID: " + course.getId() + ")");
    }
    int courseId = scanner.nextInt();
    scanner.nextLine();
    Course chosenCourse = null;
    for (Course course : courses) {
        if (course.getId() == courseId) {
            chosenCourse = course;
            break;
        }
    }
    if (chosenCourse == null) {
        System.out.println("Invalid course ID!");
        return;
    }
    List<Question> questions = getQuestionsForCourse(courseId);
    int score = 0;
    for (Question question : questions) {
        System.out.println("Question " + question.getNumber() + ": " + question.getText());
        for (int i = 0; i < question.getOptions().size(); i++) {
            System.out.println((char) ('A' + i) + ". " + question.getOptions().get(i));
        }
        System.out.println("Please enter your answer (A/B/C/D):");
        String answer = scanner.nextLine().toUpperCase();
        if (answer.equals(question.getAnswer())) {
            score++;
        }
    }
    System.out.println("Exam finished. Your score is " + score + ".");
    saveScore(studentIdDb, courseId, score);
}

private static List<Course> getAvailableCourses() {
    List<Course> courses = new ArrayList<>();
    try {
        conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
        stmt = conn.prepareStatement("SELECT id, name FROM courses");
        rs = stmt.executeQuery();
        while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            courses.add(new Course(id, name));
        }
    } catch (SQLException e) {
        System.out.println("Failed to retrieve available courses: " + e.getMessage());
    } finally {
        closeResources();
    }
    return courses;
}

private static List<Question> getQuestionsForCourse(int courseId) {
    List<Question> questions = new ArrayList<>();
    try {
        conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
        stmt = conn.prepareStatement("SELECT id, number, text, option_1, option_2, option_3, option_4, answer FROM questions WHERE course_id = ?");
        stmt.setInt(1, courseId);
        rs = stmt.executeQuery();
        while (rs.next()) {
            int id = rs.getInt("id");
            int number = rs.getInt("number");
            String text = rs.getString("text");
            List<String> options = new ArrayList<>();
            options.add(rs.getString("option_1"));
            options.add(rs.getString("option_2"));
            options.add(rs.getString("option_3"));
            options.add(rs.getString("option_4"));
            String answer = rs.getString("answer");
            questions.add(new Question(id, number, text, options, answer));
        }
    } catch (SQLException e) {
        System.out.println("Failed to retrieve questions for course: " + e.getMessage());
    } finally {
        closeResources();
    }
    return questions;
}

private static void saveScore(int studentIdDb, int courseId, int score) {
    try {
        conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
        stmt = conn.prepareStatement("INSERT INTO scores (student_id, course_id, score) VALUES (?, ?, ?)");
        stmt.setInt(1, studentIdDb);
        stmt.setInt(2, courseId);
        stmt.setInt(3, score);
        stmt.executeUpdate();
        System.out.println("Score saved!");
    } catch (SQLException e) {
        System.out.println("Failed to save score: " + e.getMessage());
    } finally {
        closeResources();
    }
}

private static void teacherMenu() {
    System.out.println("Please choose your action:");
    System.out.println("1. View questions");
    System.out.println("2. Add question");
    System.out.println("3. Delete question");
    System.out.println("4. Update question");
    System.out.println("5. Back");
    int choice = scanner.nextInt();
    scanner.nextLine();
    switch (choice) {
        case 1:
            viewQuestions();
            break;
        case 2:
            addQuestion();
            break;
        case 3:
            deleteQuestion();
            break;
        case 4:
            updateQuestion();
            break;
        case 5:
            return;
        default:
            System.out.println("Invalid choice!");
    }
}

private static void viewQuestions() {
    System.out.println("Please enter the course ID:");
    int courseId = scanner.nextInt();
    scanner.nextLine();
    List<Question> questions = getQuestionsForCourse(courseId);
    System.out.println("Questions for course " + courseId);
    for (Question question : questions) {
        System.out.println("Question " + question.getNumber() + ": " + question.getText());
        for (int i = 0; i < question.getOptions().size(); i++) {
            System.out.println((char) ('A' + i) + ". " + question.getOptions().get(i));
        }
        System.out.println("Answer: " + question.getAnswer());
    }
}

private static void addQuestion() {
    System.out.println("Please enter the course ID:");
    int courseId = scanner.nextInt();
    scanner.nextLine();
    System.out.println("Please enter the question number:");
    int number = scanner.nextInt();
    scanner.nextLine();
    System.out.println("Please enter the question text:");
    String text = scanner.nextLine();
    List<String> options = new ArrayList<>();
    for (int i = 1; i <= 4; i++) {
        System.out.println("Please enter option " + i + ":");
        options.add(scanner.nextLine());
    }
    System.out.println("Please enter the answer (A/B/C/D):");
    String answer = scanner.nextLine().toUpperCase();
    try {
        conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
        stmt = conn.prepareStatement("INSERT INTO questions (course_id, number, text, option_1, option_2, option_3, option_4, answer) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        stmt.setInt(1, courseId);
        stmt.setInt(2, number);
        stmt.setString(3, text);
        stmt.setString(4, options.get(0));
        stmt.setString(5, options.get(1));
        stmt.setString(6, options.get(2));
        stmt.setString(7, options.get(3));
        stmt.setString(8, answer);
        stmt.executeUpdate();
        System.out.println("Question added!");
    } catch (SQLException e) {
        System.out.println("Failed to add question: " + e.getMessage());
    } finally {
        closeResources();
    }
}

private static void deleteQuestion() {
    System.out.println("Please enter the question ID:");
    int questionId = scanner.nextInt();
    scanner.nextLine();
    try {
        conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
        stmt = conn.prepareStatement("DELETE FROM questions WHERE id = ?");
        stmt.setInt(1, questionId);
        int rows = stmt.executeUpdate();
        if (rows == 1) {
            System.out.println("Question deleted!");
        } else {
            System.out.println("Question not found!");
        }
    } catch (SQLException e) {
        System.out.println("Failed to delete question: " + e.getMessage());
    } finally {
        closeResources();
    }
}

private static void updateQuestion() {
    System.out.println("Please enter the question ID:");
    int questionId = scanner.nextInt();
    scanner.nextLine();
    try {
        conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
        stmt = conn.prepareStatement("SELECT id, course_id, number, text, option_1, option_2, option_3, option_4, answer FROM questions WHERE id = ?");
        stmt.setInt(1, questionId);
        rs = stmt.executeQuery();
        if (rs.next()) {
            int courseId = rs.getInt("course_id");
            int number = rs.getInt("number");
            String text = rs.getString("text");
            List<String> options = new ArrayList<>();
            options.add(rs.getString("option_1"));
            options.add(rs.getString("option_2"));
            options.add(rs.getString("option_3"));
            options.add(rs.getString("option_4"));
            String answer = rs.getString("answer");
            System.out.println("Current question:");
            System.out.println("Course ID: " + courseId);
            System.out.println("Number: " + number);
            System.out.println("Text: " + text);
            for (int i = 0; i < options.size(); i++) {
                System.out.println((char) ('A' + i) + ". " + options.get(i));
            }
            System.out.println("Answer: " + answer);
            System.out.println("Please enter the new course ID (current: " + courseId + "):");
            int newCourseId = scanner.nextInt();
            scanner.nextLine();
            System.out.println("Please enter the new question number (current: " + number + "):");
            int newNumber = scanner.nextInt();
            scanner.nextLine();
            System.out.println("Please enter the new question text (current: " + text + "):");
            String newText = scanner.nextLine();
            List<String> newOptions = new ArrayList<>();
            for (int i = 1; i <= 4; i++) {
                System.out.println("Please enter new option " + i + " (current: " + options.get(i - 1) + "):");
                newOptions.add(scanner.nextLine());
            }
            System.out.println("Please enter the new answer (A/B/C/D, current: " + answer + "):");
            String newAnswer = scanner.nextLine().toUpperCase();
            stmt = conn.prepareStatement("UPDATE questions SET course_id = ?, number = ?, text = ?, option_1 = ?, option_2 = ?, option_3 = ?, option_4 = ?, answer = ? WHERE id = ?");
            stmt.setInt(1, newCourseId);
            stmt.setInt(2, newNumber);
            stmt.setString(3, newText);
            stmt.setString(4, newOptions.get(0));
            stmt.setString(5, newOptions.get(1));
            stmt.setString(6, newOptions.get(2));
            stmt.setString(7, newOptions.get(3));
            stmt.setString(8, newAnswer);
            stmt.setInt(9, questionId);
            stmt.executeUpdate();
            System.out.println("Question updated!");
        } else {
            System.out.println("Question not found!");
        }
    } catch (SQLException e) {
        System.out.println("Failed to update question: " + e.getMessage());
    } finally {
        closeResources();
    }
}

private static void closeResources() {
    try {
        if (rs != null) {
            rs.close();
        }
        if (stmt != null) {
            stmt.close();
        }
        if (conn != null) {
            conn.close();
        }
    } catch (SQLException e) {
        System.out.println("Failed to close resources: " + e.getMessage());
    }
}

private static class Course {
    private int id;
    private String name;
    
    public Course(int id, String name) {
        this.id = id;
        this.name = name;
    }
    
    public int getId() {
        return id;
    }
    
    public String getName() {
        return name;
    }
}

private static class Question {
    private int id;
    private int number;
    private String text;
    private List<String> options;
    private String answer;
    
    public Question(int id, int number, String text, List<String> options, String answer) {
        this.id = id;
        this.number = number;
        this.text = text;
        this.options = options;
        this.answer = answer;
    }
    
    public int getId() {
        return id;
    }
    
    public int getNumber() {
        return number;
    }
    
    public String getText() {
        return text;
    }
    
    public List<String> getOptions() {
        return options;
    }
    
    public String getAnswer() {
        return answer;
    }
}

}

Java and MySQL Exam Portal: Student Registration, Login, and Exam System