[go: up one dir, main page]

0% found this document useful (0 votes)
38 views31 pages

Advance Java Micro

Uploaded by

sanskrutinile06
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views31 pages

Advance Java Micro

Uploaded by

sanskrutinile06
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

S.H.

JONDHALE POLYTECHNIC

SUBJECT NAME:ADVANCE JAVA PROGRAMING

DEPARTMENT:COMPUTER

SEMESTER:5TH

MICRO PROJECT TITLE: MCQ TEST PLATFORM FOR JAVA

YEAR: 2024-25

PREPARED BY:
1. SANSKRUTI NILE [1503]

UNDER THE GUIDANCE OF: Prof. MRS.NEHA MOHOLKAR

1
Maharashtra State Board of Technical Education
Certificate

This is to certify that


Ms Sanskruti Nile
Of fifth Semester of Diploma in computer engineering of
Institute S.H.Jondhale polytechnic has
Successfully completed Micro-project work in subject
Advance java programing for the academic year 2024-2025 as
prescribed in the I-Scheme Curriculum

Place:Dombivili Enrollment no:2200440051


Date: Exam seat no:

Signature Signature Signature


Of Of Of
Project guide HOD Principal

Seal of institute

2
ACKNOWLEDGMENT

We wish to express our profound gratitude to our guide Mrs. Neha


Moholkar who guided us endlessly in the framing and completion of
the micro project. she guided us on all the main points in that micro
project. We are indebted to her constant encouragement, cooperation,
and help. It was her enthusiastic support that helped us in overcoming
various obstacles in the micro-project.We are also thankful to our
Principal, HOD, faculty members and classmates of department
for extending their support and motivation in the completion of this
micro-project.

Names of Team Members with Roll Nos.


1. Sanskruti Nile [1503]

3
ABSTRACT
This project, titled "MCQ Test Platform For Java," is designed to help users test
their knowledge through multiple-choice questions (MCQs) on various topics. It
offers a user-friendly interface with functionalities like user account creation,
secure login, and chapter-based MCQ practice. The system consists of six
chapters, . After successfully logging in, users can select a chapter and attempt
all questions displayed at once in a scrollable panel, providing a seamless
quiz-taking experience.

The system checks user inputs and calculates the score upon submission. This
Java application integrates essential GUI components using Swing for layout
management and form handling. It efficiently tracks users' progress and allows
for the creation of multiple accounts, ensuring personalized experiences. The
program's back-end ensures proper validation of user credentials and stores
account information for secure access.

This mini-project demonstrates the practical implementation of fundamental


programming concepts such as event handling, user input validation, and
graphical user interface (GUI) development in Java. It is an ideal tool for
students to enhance their knowledge in Java and other technical subjects, while
also learning how to build interactive applications with real-world functionality.

4
ACTION PLAN
Sr. Wee Details of activity Planned Planned Name of Responsible
No. k Start date Finish Team
date Members
1 1 & Discussion and finalization of the
2 topic. 1\8\24 10\8\24 sanskruti

2 3 Preparation of the abstract


11\8\24 17\8\24 sanskruti

3 4 Literature review
18\8\24 24\8\24 sanskruti

4 5 Submission of micro project


proposal (Annexure I) 25\8\24 31\8\24 sanskruti

5 6 Collection of the information on


the topic. 1\9\24 7\9\25 sanskruti

6 7 Collection of all relevant content /


materials for the execution of the 8\9\24 14\9\24 sanskruti
project.

7 8 Discussion and submission of


outline of the project. 15\9\25 21\9\24 sanskruti

8 9 Analysis/execution of collected
data/information and Preparation of 22\9\24 28\924 sanskruti
prototypes/drawings/charts/graphs/
tables/models/circuits/programs
etc.
9 10 Compilation of contents of project
29\9\24 5\10\24 sanskruti

10 11 Compilation of weekly progress


report 6\10\24 12\10\24 sanskruti

11 12 Preparation of the project report


(Annexure II) 13\10\24 19\10\24 sanskruti

12 13 Viva Voce / Delivery of


presentation. 20\10\24 \11\24 sanskruti

5
INDEX

Sr.No Topic Pgno


1. Introduction 7
2. Requirements analysis and System 8
specifications

3. Design approach 9
5. Source code 10-25
6. Overview of code 26
7. Output 27-28
8. Future Scope 29
8. Conclusion 30
10. Reference 31

6
INTRODUCTION

Advanced Java refers to the higher-level programming concepts and


frameworks that extend beyond the basic principles of the Java programming
language. While Core Java focuses on fundamental constructs such as data
types, control structures, and basic object-oriented programming, Advanced
Java encompasses specialized areas that include GUI development, networking,
database connectivity, and web technologies. Key components such as Java
Database Connectivity (JDBC) facilitate interaction with databases, while Java
Server Pages (JSP) and Servlets allow developers to create dynamic web
applications. Mastery of these concepts empowers developers to build robust
applications that can cater to complex business requirements.

The project serves as a practical implementation of Advanced Java concepts.


This application is designed primarily for students and learners to assess their
understanding of various topics through multiple-choice questions organized by
chapter. With a focus on six chapters, each containing ten carefully curated
questions, the application aims to create an engaging and informative learning
experience. Users can create accounts, log in, and select specific chapters to
practice, thereby personalizing their learning journey.

The application employs a graphical user interface (GUI) built using Swing,
ensuring that it is both intuitive and user-friendly. After logging in, users are
presented with a scrollable interface that displays all questions at once, allowing
for a comprehensive review of the material. Each question includes radio
buttons for selecting answers, promoting efficient input and usability. Upon
submission, users receive immediate feedback with their score, enhancing the
learning experience. This project not only showcases practical skills in
Advanced Java but also emphasizes the importance of creating functional,
real-world applications that facilitate learning and knowledge assessment. By
implementing user authentication, the project underscores the significance of
data security and user management in software development.

7
REQUIREMENT ANALYSIS AND SYSTEM SPECIFICATION

Resource name Specification Quantity


Laptop Minimum 4 GB 1
RAM, 50 GB
available storage,
Operating System Mac os 1
Documentation Tool Google Docs 1
Advance java Nirali Prakashan 1
textbook

8
DESIGN APPROACH
The MCQ Test Platform for Java is designed with a user-centric approach,
emphasizing simplicity, accessibility, and engagement. The application is built
using Java's Swing framework, providing a graphical user interface (GUI) that
is intuitive and easy to navigate. The design consists of two main
functionalities: account management and a multiple-choice question (MCQ)
testing system. The account management feature allows users to create and log
in to their accounts, while the MCQ testing feature enables users to select
chapters and answer questions related to those topics. Each chapter contains ten
questions, ensuring comprehensive coverage of the subject matter.

The application's architecture follows a modular design, allowing for easy


scalability and maintainability. Each module corresponds to a specific
functionality—such as user authentication, question handling, and score
calculation. The use of Java's Swing components, such as JFrame, JPanel, and
JOptionPane, enhances the user experience by providing interactive elements
like buttons, text fields, and scrollable areas for questions. The design also
incorporates error handling to ensure robust input validation, guiding users
through the account creation and login processes.

To enhance usability, the project integrates a scrollable interface for the question
display, allowing users to view all questions at once, thereby improving
engagement and reducing navigation complexity. This design choice caters to
users' preference for a holistic view of their progress during the test. The
implementation of radio buttons for selecting answers simplifies the interaction
process, making it straightforward for users to submit their responses. Overall,
the design approach prioritizes user experience while leveraging Java's
capabilities to create a functional and educational tool for mastering Java
concepts through self-assessment.

9
SOURCE CODE
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MCQApp {


// Database configuration
private static final String DB_URL = "jdbc:mysql://localhost:3306/mcq_db";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "";

private static final String[][] QUESTIONS_CHAPTERS = {


{
"1. What does AWT stand for?\nA. Abstract Window Toolkit\nB. Abstract
Windowing Tool\nC. Application Window Tool\nD. None of the above",
"2. Which method is used to set the title of a frame?\nA. setTitle()\nB.
setFrameTitle()\nC. setTitleFrame()\nD. titleFrame()",
"3. Which class is the top-level container in AWT?\nA. JFrame\nB.
JFrameContainer\nC. Frame\nD. AWTFrame",
"4. What layout manager is used by default in a JFrame?\nA. FlowLayout\nB.
BorderLayout\nC. GridLayout\nD. BoxLayout",
"5. Which method is used to make a frame visible?\nA. setVisible()\nB.
showFrame()\nC. display()\nD. openFrame()",
"6. What is the main function of the Button class?\nA. To perform actions\nB. To
display images\nC. To hold text\nD. To create frames",
"7. Which package contains AWT classes?\nA. javax.swing\nB. java.awt\nC.
java.swing\nD. java.awt.event",
"8. How do you create a button in AWT?\nA. new Button()\nB. new
ButtonClass()\nC. Button()\nD. new AWTButton()",
"9. What does the term 'Event' refer to in AWT?\nA. User actions\nB. GUI
components\nC. Data storage\nD. Layout managers",

10
"10. Which method is used to add components to a frame?\nA. addComponent()\nB.
add()\nC. insert()\nD. append()"
},
{
"1. What does Swing provide?\nA. Lightweight components\nB. Heavyweight
components\nC. Only AWT components\nD. No components",
"2. Which class is a top-level container in Swing?\nA. JFrame\nB. Frame\nC.
Window\nD. JPanel",
"3. Which method is used to create a JButton?\nA. new JButton()\nB.
JButton.create()\nC. JButton()\nD. createButton()",
"4. What is the default layout manager for JPanel?\nA. FlowLayout\nB.
BorderLayout\nC. GridLayout\nD. BoxLayout",
"5. How do you change the background color of a JPanel?\nA.
setBackgroundColor()\nB. setBackground()\nC. changeColor()\nD. colorBackground()",
"6. What is the purpose of the JLabel class?\nA. To display text\nB. To create
buttons\nC. To hold input\nD. To layout components",
"7. Which method is used to get the text from a JTextField?\nA. getTextField()\nB.
getText()\nC. retrieveText()\nD. fetchText()",
"8. What is the function of JRadioButton?\nA. To create multiple selections\nB. To
allow single selections\nC. To display images\nD. To hold text",
"9. How do you group JRadioButton objects?\nA. By using a ButtonGroup\nB. By
using a JPanel\nC. By using a layout manager\nD. By using a checkbox",
"10. What is the main advantage of using Swing over AWT?\nA. Swing is faster\nB.
Swing is lightweight\nC. AWT is better\nD. Swing has no advantages"
},
{
"1. What is an event listener?\nA. A component that listens to events\nB. A part of the
GUI\nC. A method in AWT\nD. An object that generates events",
"2. How do you add an ActionListener to a button?\nA. button.addListener()\nB.
button.addActionListener()\nC. button.listener()\nD. button.attachListener()",
"3. What is the purpose of the actionPerformed method?\nA. To trigger an event\nB.
To handle events\nC. To create a button\nD. To show messages",
"4. Which interface is used for handling mouse events?\nA. MouseListener\nB.
MouseAdapter\nC. MouseEvent\nD. ActionListener",
"5. What is a mouse click considered?\nA. A single event\nB. A double event\nC. A
compound event\nD. A sequential event",
"6. How do you remove an event listener?\nA. removeListener()\nB.
removeActionListener()\nC. detachListener()\nD. deleteListener()",
"7. What is the difference between an event and an event source?\nA. An event is the
source of actions\nB. An event source generates events\nC. An event is a method\nD. An
event source is not needed",
"8. What method do you use to trigger an event?\nA. fire()\nB. trigger()\nC.
action()\nD. notify()",

11
"9. What are the two types of events in AWT?\nA. Mouse and keyboard\nB. Action
and state\nC. User and system\nD. Timer and action",
"10. How do you make a component focusable?\nA. setFocusable()\nB.
setFocus()\nC. requestFocus()\nD. enableFocus()"
},
{
"1. What is a TCP socket?\nA. A connection-oriented protocol\nB. A connectionless
protocol\nC. A GUI component\nD. None of the above",
"2. How do you create a Socket object in Java?\nA. new Socket()\nB.
Socket.create()\nC. new SocketObject()\nD. createSocket()",
"3. What is the purpose of the ServerSocket class?\nA. To create a server\nB. To send
data\nC. To listen for incoming connections\nD. To close connections",
"4. How do you establish a connection to a server?\nA. connect()\nB. open()\nC.
accept()\nD. Socket.connect()",
"5. What is the difference between TCP and UDP?\nA. TCP is faster\nB. UDP is
connection-oriented\nC. TCP is reliable\nD. No difference",
"6. How do you send data through a socket?\nA. write()\nB. send()\nC. transmit()\nD.
push()",
"7. What method do you use to close a socket?\nA. closeSocket()\nB. terminate()\nC.
close()\nD. end()",
"8. How do you receive data through a socket?\nA. read()\nB. getData()\nC.
retrieve()\nD. accept()",
"9. What is the purpose of the InputStream class?\nA. To read data\nB. To write
data\nC. To process events\nD. To create connections",
"10. How do you handle exceptions in socket programming?\nA. Use try-catch\nB.
Use throws\nC. Ignore them\nD. Log them"
},
{
"1. What is JDBC?\nA. Java Database Connectivity\nB. Java Data Connection\nC.
Java Database Communication\nD. None of the above",
"2. Which driver is used for MySQL?\nA. MySQLDriver\nB.
com.mysql.jdbc.Driver\nC. MySQLConnector\nD. java.sql.Driver",
"3. How do you establish a connection to a database?\nA.
DriverManager.getConnection()\nB. ConnectionManager.connect()\nC.
Database.connect()\nD. connectDatabase()",
"4. What method do you use to execute a query?\nA. executeQuery()\nB.
runQuery()\nC. execute()\nD. query()",
"5. How do you retrieve data from a ResultSet?\nA. getData()\nB. fetch()\nC.
retrieve()\nD. get()",
"6. What is a PreparedStatement?\nA. A pre-compiled SQL statement\nB. A type of
ResultSet\nC. A method for executing statements\nD. None of the above",
"7. What is the difference between Statement and PreparedStatement?\nA. Statement
is faster\nB. PreparedStatement is pre-compiled\nC. Both are the same\nD. None of the
above",

12
"8. How do you handle SQL exceptions?\nA. Use try-catch\nB. Use throws\nC.
Ignore them\nD. Log them",
"9. What method is used to close a Connection?\nA. closeConnection()\nB.
terminate()\nC. close()\nD. end()",
"10. What does CRUD stand for?\nA. Create, Read, Update, Delete\nB. Create,
Retrieve, Update, Delete\nC. Create, Read, Upload, Delete\nD. Create, Read, Update, Drop"
},
{
"1. What does API stand for?\nA. Application Programming Interface\nB.
Application Protocol Interface\nC. Application Performance Indicator\nD. None of the
above",
"2. Which HTTP method is used to retrieve data?\nA. POST\nB. GET\nC. PUT\nD.
DELETE",
"3. What is REST?\nA. Representational State Transfer\nB. Remote Event State
Transfer\nC. Remote Service Transfer\nD. None of the above",
"4. What does JSON stand for?\nA. JavaScript Object Notation\nB. JavaScript Object
Notation\nC. JavaScript Open Notation\nD. None of the above",
"5. What is the purpose of an API?\nA. To create databases\nB. To provide a way for
applications to communicate\nC. To manage user interfaces\nD. None of the above",
"6. What is a web service?\nA. A software system designed to support interoperable
machine-to-machine interaction\nB. A service that is hosted on the web\nC. A database
management system\nD. None of the above",
"7. How is data usually formatted in an API response?\nA. XML\nB. JSON\nC. Both
A and B\nD. None of the above",
"8. What is an endpoint?\nA. The URL at which an API can be accessed\nB. A
method in a class\nC. A type of response\nD. None of the above",
"9. What is an API key?\nA. A secret token for authentication\nB. A public key for
encryption\nC. A unique identifier for a user\nD. None of the above",
"10. What is the status code for a successful HTTP request?\nA. 404\nB. 200\nC.
500\nD. 301"
}
};

private static final String[][] CORRECT_ANSWERS = {


{"A", "A", "C", "B", "A", "A", "B", "A", "A", "B"}, // Chapter 1: AWT
{"A", "A", "A", "A", "B", "A", "B", "B", "A", "B"}, // Chapter 2: Swing
{"A", "B", "B", "A", "A", "B", "B", "A", "C", "A"}, // Chapter 3: Event Handling
{"A", "A", "C", "C", "C", "A", "C", "A", "A", "A"}, // Chapter 4: Sockets
{"A", "B", "A", "A", "D", "A", "B", "A", "C", "A"}, // Chapter 5: JDBC
{"A", "B", "A", "A", "B", "A", "C", "A", "A", "B"} // Chapter 6: APIs
};

13
private static final String[] CHAPTERS = {
"Chapter 1: AWT",
"Chapter 2: Swing",
"Chapter 3: Event Handling",
"Chapter 4: Sockets",
"Chapter 5: JDBC",
"Chapter 6: APIs"
};

private static JFrame frame;


private static JTextArea scoreArea;
private static String currentUser;
private static List<JRadioButton[]> questionResponses;
private static final Map<String, Map<String, Integer>> userScores = new HashMap<>();

private static class UserProfile {


String fullName;
String email;
String phoneNumber;
String password;

public UserProfile(String fullName, String email, String phoneNumber, String


password) {
this.fullName = fullName;
this.email = email;
this.phoneNumber = phoneNumber;
this.password = password;
}
}

// Database connection method


private static Connection getConnection() throws SQLException {
return DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
}

public static void main(String[] args) {


// Load the JDBC driver
try {
// String driverPath = System.getProperty("user.dir") +
"/lib/mysql-connector-java-8.0.26.jar";
// System.out.println("Looking for driver at: " + driverPath);
//
// // Add the driver to system classpath
// java.net.URLClassLoader classLoader = new java.net.URLClassLoader(

14
// new java.net.URL[] { new java.io.File(driverPath).toURI().toURL() },
// TestConnection.class.getClassLoader()
// );

// Load the driver


Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("Driver loaded successfully!");

} catch (Exception e) {
System.out.println("Error loading driver: " + e.getMessage());
e.printStackTrace();
return;
}

SwingUtilities.invokeLater(() -> {
frame = new JFrame("MCQ Test Platform");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 800);
frame.setLocationRelativeTo(null);
showLogin();
frame.setVisible(true);
});
}

private static void showLogin() {


JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);

JTextField userIdField = new JTextField(20);


JPasswordField passwordField = new JPasswordField(20);

gbc.gridx = 0; gbc.gridy = 0;
panel.add(new JLabel("User ID:"), gbc);
gbc.gridx = 1;
panel.add(userIdField, gbc);

gbc.gridx = 0; gbc.gridy = 1;
panel.add(new JLabel("Password:"), gbc);
gbc.gridx = 1;
panel.add(passwordField, gbc);

JButton loginButton = new JButton("Login");


JButton createAccountButton = new JButton("Create New Account");

15
loginButton.addActionListener(e -> {
String userId = userIdField.getText().trim();
String password = new String(passwordField.getPassword());

try {
if (validateLogin(userId, password)) {
currentUser = userId;
if (!userScores.containsKey(userId)) {
userScores.put(userId, new HashMap<>());
}
loadUserScores(userId);
showChapterSelection();
} else {
JOptionPane.showMessageDialog(frame,
"Invalid credentials. Please try again.",
"Error",
JOptionPane.ERROR_MESSAGE);
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(frame,
"Database error: " + ex.getMessage(),
"Error",
JOptionPane.ERROR_MESSAGE);
}
});

createAccountButton.addActionListener(e -> showAccountCreation());

gbc.gridx = 0; gbc.gridy = 2; gbc.gridwidth = 2;


panel.add(loginButton, gbc);
gbc.gridy = 3;
panel.add(createAccountButton, gbc);

frame.setContentPane(panel);
frame.revalidate();
}

private static boolean validateLogin(String userId, String password) throws SQLException


{
try (Connection conn = getConnection()) {
String sql = "SELECT * FROM users WHERE user_id = ? AND password = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, userId);

16
pstmt.setString(2, password);

return pstmt.executeQuery().next();
}
}

private static void loadUserScores(String userId) throws SQLException {


try (Connection conn = getConnection()) {
String sql = "SELECT chapter, score FROM scores WHERE user_id = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, userId);

ResultSet rs = pstmt.executeQuery();
Map<String, Integer> scores = userScores.get(userId);
while (rs.next()) {
scores.put(rs.getString("chapter"), rs.getInt("score"));
}
}
}

private static void showAccountCreation() {


JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.fill = GridBagConstraints.HORIZONTAL;

JTextField fullNameField = new JTextField(20);


JTextField emailField = new JTextField(20);
JTextField phoneField = new JTextField(20);
JTextField userIdField = new JTextField(20);
JPasswordField passwordField = new JPasswordField(20);
JPasswordField confirmPasswordField = new JPasswordField(20);

// Add components to panel


gbc.gridx = 0; gbc.gridy = 0;
panel.add(new JLabel("Full Name:"), gbc);
gbc.gridx = 1;
panel.add(fullNameField, gbc);

gbc.gridx = 0; gbc.gridy = 1;
panel.add(new JLabel("Email:"), gbc);
gbc.gridx = 1;
panel.add(emailField, gbc);

17
gbc.gridx = 0; gbc.gridy = 2;
panel.add(new JLabel("Phone Number:"), gbc);
gbc.gridx = 1;
panel.add(phoneField, gbc);

gbc.gridx = 0; gbc.gridy = 3;
panel.add(new JLabel("User ID:"), gbc);
gbc.gridx = 1;
panel.add(userIdField, gbc);

gbc.gridx = 0; gbc.gridy = 4;
panel.add(new JLabel("Password:"), gbc);
gbc.gridx = 1;
panel.add(passwordField, gbc);

gbc.gridx = 0; gbc.gridy = 5;
panel.add(new JLabel("Confirm Password:"), gbc);
gbc.gridx = 1;
panel.add(confirmPasswordField, gbc);

JButton createButton = new JButton("Create Account");


JButton backButton = new JButton("Back to Login");

createButton.addActionListener(e -> {
String fullName = fullNameField.getText().trim();
String email = emailField.getText().trim();
String phone = phoneField.getText().trim();
String userId = userIdField.getText().trim();
String password = new String(passwordField.getPassword());
String confirmPass = new String(confirmPasswordField.getPassword());

// Validation
if (fullName.isEmpty() || email.isEmpty() || phone.isEmpty() ||
userId.isEmpty() || password.isEmpty()) {
JOptionPane.showMessageDialog(frame,
"All fields are required.",
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}

if (!email.matches("^[A-Za-z0-9+_.-]+@(.+)$")) {
JOptionPane.showMessageDialog(frame,
"Please enter a valid email address.",

18
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}

if (!phone.matches("\\d{10}")) {
JOptionPane.showMessageDialog(frame,
"Please enter a valid 10-digit phone number.",
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}

if (!password.equals(confirmPass)) {
JOptionPane.showMessageDialog(frame,
"Passwords do not match.",
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}

try {
createNewUser(userId, password, fullName, email, phone);
JOptionPane.showMessageDialog(frame,
"Account created successfully! You can now log in.",
"Success",
JOptionPane.INFORMATION_MESSAGE);
showLogin();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(frame,
"Error creating account: " + ex.getMessage(),
"Error",
JOptionPane.ERROR_MESSAGE);
}
});

backButton.addActionListener(e -> showLogin());

gbc.gridx = 0; gbc.gridy = 6; gbc.gridwidth = 2;


panel.add(createButton, gbc);
gbc.gridy = 7;
panel.add(backButton, gbc);

frame.setContentPane(panel);

19
frame.revalidate();
}

private static void createNewUser(String userId, String password, String fullName,


String email, String phone) throws SQLException {
try (Connection conn = getConnection()) {
String sql = "INSERT INTO users (user_id, password, full_name, email, phone) " +
"VALUES (?, ?, ?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, userId);
pstmt.setString(2, password);
pstmt.setString(3, fullName);
pstmt.setString(4, email);
pstmt.setString(5, phone);

pstmt.executeUpdate();
}
}

private static void showChapterSelection() {


JPanel mainPanel = new JPanel(new BorderLayout());
JPanel chapterPanel = new JPanel(new GridLayout(0, 1, 5, 5));
chapterPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

// Display user profile information


try {
UserProfile profile = getUserProfile(currentUser);
JTextArea userInfoArea = new JTextArea();
userInfoArea.setEditable(false);
userInfoArea.setBackground(frame.getBackground());
userInfoArea.setText(String.format("Welcome, %s!\nEmail: %s\nPhone: %s\n\nYour
Scores:\n",
profile.fullName, profile.email, profile.phoneNumber));

Map<String, Integer> scores = userScores.get(currentUser);


for (String chapter : CHAPTERS) {
Integer score = scores.get(chapter);
userInfoArea.append(chapter + ": " + (score != null ? score + "/10" : "Not
attempted") + "\n");
}

mainPanel.add(new JScrollPane(userInfoArea), BorderLayout.NORTH);


} catch (SQLException ex) {
JOptionPane.showMessageDialog(frame,

20
"Error loading user profile: " + ex.getMessage(),
"Error",
JOptionPane.ERROR_MESSAGE);
}

for (String chapter : CHAPTERS) {


JButton chapterButton = new JButton(chapter);
chapterButton.addActionListener(e -> startQuiz(chapter));

Integer chapterScore = userScores.get(currentUser).get(chapter);


if (chapterScore != null) {
chapterButton.setText(chapter + " (Previous Score: " + chapterScore + "/10)");
}

chapterPanel.add(chapterButton);
}

JButton logoutButton = new JButton("Logout");


logoutButton.addActionListener(e -> {
currentUser = null;
showLogin();
});

mainPanel.add(new JScrollPane(chapterPanel), BorderLayout.CENTER);


mainPanel.add(logoutButton, BorderLayout.SOUTH);

frame.setContentPane(mainPanel);
frame.revalidate();
}

private static UserProfile getUserProfile(String userId) throws SQLException {


try (Connection conn = getConnection()) {
String sql = "SELECT * FROM users WHERE user_id = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, userId);

ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
return new UserProfile(
rs.getString("full_name"),
rs.getString("email"),
rs.getString("phone"),
rs.getString("password")
);

21
}
throw new SQLException("User profile not found");
}
}
private static void startQuiz(String chapter) {
int chapterIndex = getChapterIndex(chapter);
questionResponses = new ArrayList<>();

JPanel mainPanel = new JPanel(new BorderLayout());


JPanel questionsPanel = new JPanel();
questionsPanel.setLayout(new BoxLayout(questionsPanel, BoxLayout.Y_AXIS));

scoreArea = new JTextArea();


scoreArea.setEditable(false);
scoreArea.setBackground(frame.getBackground());
questionsPanel.add(scoreArea);

for (String question : QUESTIONS_CHAPTERS[chapterIndex]) {


JPanel questionPanel = new JPanel();
questionPanel.setLayout(new BoxLayout(questionPanel, BoxLayout.Y_AXIS));
questionPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

questionPanel.add(new JLabel("<html><body style='width: 400px'>" + question +


"</body></html>"));
JRadioButton[] answerOptions = createAnswerOptions();
questionResponses.add(answerOptions);

for (JRadioButton option : answerOptions) {


questionPanel.add(option);
}
questionsPanel.add(questionPanel);
}

JPanel buttonPanel = new JPanel(new FlowLayout());


JButton submitButton = new JButton("Submit");
JButton backButton = new JButton("Back to Chapters");

submitButton.addActionListener(e -> calculateAndSaveScore(chapterIndex, chapter));


backButton.addActionListener(e -> showChapterSelection());

buttonPanel.add(submitButton);
buttonPanel.add(backButton);

mainPanel.add(new JScrollPane(questionsPanel), BorderLayout.CENTER);

22
mainPanel.add(buttonPanel, BorderLayout.SOUTH);

frame.setContentPane(mainPanel);
frame.revalidate();
}

private static JRadioButton[] createAnswerOptions() {


JRadioButton[] options = new JRadioButton[4];
ButtonGroup group = new ButtonGroup();
for (int i = 0; i < 4; i++) {
options[i] = new JRadioButton(String.valueOf((char) ('A' + i)));
group.add(options[i]);
}
return options;
}

private static void calculateAndSaveScore(int chapterIndex, String chapter) {


int score = 0;
String[] answers = CORRECT_ANSWERS[chapterIndex];
StringBuilder sb = new StringBuilder();
sb.append("Quiz Results:\n");

for (int i = 0; i < questionResponses.size(); i++) {


JRadioButton[] options = questionResponses.get(i);
String selectedAnswer = null;
for (JRadioButton option : options) {
if (option.isSelected()) {
selectedAnswer = option.getText();
break;
}
}

if (selectedAnswer == null) {
sb.append("Q").append(i + 1).append(": Not answered\n");
} else if (answers[i].equals(selectedAnswer)) {
score++;
sb.append("Q").append(i + 1).append(": Correct\n");
} else {
sb.append("Q").append(i + 1).append(": Incorrect. Correct answer is
").append(answers[i]).append("\n");
}
}

sb.append("\nFinal Score: ").append(score).append("/10");

23
try {
saveScore(currentUser, chapter, score);
userScores.get(currentUser).put(chapter, score);
JOptionPane.showMessageDialog(frame, sb.toString(), "Quiz Results",
JOptionPane.INFORMATION_MESSAGE);
showChapterSelection();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(frame,
"Error saving score: " + ex.getMessage(),
"Error",
JOptionPane.ERROR_MESSAGE);
}
}

private static void saveScore(String userId, String chapter, int score) throws SQLException
{
try (Connection conn = getConnection()) {
// First check if a score already exists
String checkSql = "SELECT id FROM scores WHERE user_id = ? AND chapter =
?";
PreparedStatement checkStmt = conn.prepareStatement(checkSql);
checkStmt.setString(1, userId);
checkStmt.setString(2, chapter);
ResultSet rs = checkStmt.executeQuery();

if (rs.next()) {
// Update existing score
String updateSql = "UPDATE scores SET score = ?, attempt_date =
CURRENT_TIMESTAMP WHERE user_id = ? AND chapter = ?";
PreparedStatement updateStmt = conn.prepareStatement(updateSql);
updateStmt.setInt(1, score);
updateStmt.setString(2, userId);
updateStmt.setString(3, chapter);
updateStmt.executeUpdate();
} else {
// Insert new score
String insertSql = "INSERT INTO scores (user_id, chapter, score) VALUES (?, ?,
?)";
PreparedStatement insertStmt = conn.prepareStatement(insertSql);
insertStmt.setString(1, userId);
insertStmt.setString(2, chapter);
insertStmt.setInt(3, score);
insertStmt.executeUpdate();

24
}
}
}

private static int getChapterIndex(String chapter) {


for (int i = 0; i < CHAPTERS.length; i++) {
if (CHAPTERS[i].equals(chapter)) {
return i;
}
}
return -1;
}
}

25
OVERVIEW OF CODE
1. Data Definitions:
○ QUESTIONS: Arrays of questions for each chapter.
○ ANSWERS: Corresponding correct answers for each question.
2. Main Application (MCQApp):
○ The main method initializes the GUI.
○ Components include JTextField for username, JPasswordField for
password, and buttons for creating accounts and logging in.
3. Action Listeners:
○ CreateAccountListener: Handles account creation, ensuring the
username and password fields are filled and checking for existing
usernames.
○ LoginListener: Validates user credentials and proceeds to the quiz
if successful.
4. Quiz Functionality:
○ showPracticeOptions(): Presents the user with chapter options and
displays corresponding questions in a scrollable dialog.
○ SubmitListener: Evaluates the answers when the user submits their
responses, displaying the final score.

How It Works

1. Account Creation: Users enter a username and password. If successful,


the account is stored in a HashMap.
2. Login: Users log in with their credentials. If valid, they can select a
chapter to take a quiz.
3. Quiz Interface: Questions are displayed in a scrollable panel with radio
buttons for answers.
4. Scoring: Upon submission, the application calculates the score based on
the selected answers and displays it.

26
OUTPUT
Account creation :-

Login :-

Menu after login:-

27
Mcq list :-

Submit process:-

28
FUTURE SCOPE

The future scope of your MCQ Test Platform for Java can be significantly
expanded to enhance functionality and user experience. Consider implementing
user accounts and profiles for personalized tracking of progress and
performance. A dynamic question management system could allow
administrators to easily update the question bank, while adaptive learning
features could offer personalized quizzes based on user performance. Integrating
detailed reporting and analytics would provide insights into user strengths and
weaknesses, while supporting multimedia content can create engaging quizzes.
Developing a mobile application could improve accessibility, and gamification
elements like leaderboards and badges could boost user engagement.
Incorporating social features and integration with Learning Management
Systems (LMS) can broaden the platform’s appeal, while ensuring accessibility
and multi-language support would make it more inclusive. Lastly, a robust
feedback mechanism for users and regular data backups would ensure a
continuously improving and secure platform. These enhancements can
transform your application into a comprehensive educational tool that caters to a
diverse audience and promotes an interactive learning experience.

29
CONCLUSION

In conclusion, the MCQ Test Platform for Java serves as an innovative


educational tool that effectively combines interactive learning with user-friendly
design. By allowing users to create accounts, select chapters, and participate in
multiple-choice quizzes, it not only reinforces core concepts in Java but also
enhances user engagement through a straightforward interface. The integration
of various chapters on essential topics, such as AWT, Swing, Event Handling,
TCP Sockets, JDBC, and Servlets, ensures a comprehensive understanding of
Java programming. Furthermore, the potential for future enhancements—such
as personalized learning experiences, mobile accessibility, and advanced
analytics—positions the platform as a valuable resource in the field of
education. As technology continues to evolve, this platform can adapt to meet
the changing needs of learners, promoting continuous growth and development
in programming skills. Overall, this project not only emphasizes the importance
of knowledge assessment but also fosters a deeper understanding of Java,
equipping users with the tools necessary for success in their programming
endeavors.

30
REFERENCE

● www.google.com
● www.studoc.com
● www.greeksforgreeks.com
● www.scrib.com
● www.wordpress.com

31

You might also like