-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChapter1.java
More file actions
227 lines (205 loc) · 12.5 KB
/
Copy pathChapter1.java
File metadata and controls
227 lines (205 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import javax.swing.*; // Import Swing components for GUI
import java.awt.*; // Import AWT for layout and graphics
import java.sql.Connection; // Import for SQL connection
import java.sql.DriverManager; // Import for managing SQL driver
import java.sql.PreparedStatement; // Import for prepared SQL statements
public class chapter1 extends JFrame {
private static String username; // Field to store the username
private HomePage homePage; // Reference to the HomePage instance
private JPanel panel; // Main panel for the GUI
private JTextArea questionLabel; // Text area for displaying questions
private JRadioButton[] options; // Array of radio buttons for answer options
private ButtonGroup group; // Group to manage radio button selection
private JButton nextButton; // Button to go to the next question
private JButton previousButton; // Button to go back to the previous question
@Override
public void setVisible(boolean b) {
super.setVisible(b); // Call the superclass method to set visibility
}
// Array of questions for the quiz
private String[] questions = {
"What is the main function of an operating system (OS) in a computer?",
"Which of these is NOT an example of an operating system?",
"What is the purpose of the Java Development Kit (JDK)?",
"In Java, what is the purpose of the 'main' method?",
"Which of the following is a reserved word in Java?",
"In Java, which character is used to terminate each statement?",
"What type of error is caused by dividing a number by zero in Java?",
"What is 'bytecode' in the Java programming process?",
"Which tool would you use to create, compile, and run Java programs?",
"What is a common practice for enhancing readability in Java code?"
};
// 2D array of answer options for each question
private String[][] optionsForQuestions = {
{"A. Runs application programs without errors", "B. Manages and controls the computer’s activities", "C. Provides internet access", "D. Compiles programming code"},
{"A. Microsoft Windows", "B. Mac OS", "C. Google Chrome", "D. Linux"},
{"A. Provides a runtime environment for Java programs", "B. Allows Java code to be written and executed", "C. Manages operating systems", "D. Is used exclusively for debugging Java programs"},
{"A. Stores data for the program", "B. Starts the execution of a Java program", "C. Compiles the program", "D. Displays errors in the code"},
{"A. System", "B. Main", "C. Class", "D. Print"},
{"A. Colon (:)", "B. Period (.)", "C. Semicolon (;)", "D. Exclamation mark (!)" },
{"A. Syntax error", "B. Runtime error", "C. Logic error", "D. None of the above"},
{"A. The final executable code", "B. A compiled form of Java code", "C. A code generated by the OS", "D. A code that causes syntax errors"},
{"A. Notepad", "B. Browser", "C. IDE", "D. File Manager"},
{"A. Using single spaces between lines of code", "B. Indenting two spaces and using blank lines to separate code segments", "C. Writing all code in a single line", "D. Avoiding comments to reduce code length"}
};
private String[] correctAnswers = {"B", "C", "B", "B", "C", "C", "B", "B", "C", "B"}; // Array of correct answers
private int currentQuestionIndex = 0; // Index of the current question
private int score = 0; // User's score
private String[] selectedAnswers = new String[10]; // Array to store user's selected answers
// Constructor for the chapter1 class
public chapter1(String username, HomePage homePage) {
this.username = username; // Initialize username
this.homePage = homePage; // Initialize homePage reference
setTitle("Java Quiz - Chapter 1"); // Set the window title
setSize(800, 600); // Set the window size
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Close application on exit
getContentPane().setBackground(new Color(50, 64, 113)); // Set background color
panel = new JPanel(); // Create a new panel
panel.setLayout(null); // Use absolute positioning for custom placements
panel.setOpaque(false); // Make the panel transparent
// Set up the question label
questionLabel = new JTextArea();
questionLabel.setFont(new Font("Arial Rounded MT Bold", Font.PLAIN, 24)); // Set font style and size
questionLabel.setForeground(Color.WHITE); // Set text color
questionLabel.setOpaque(false); // Make it transparent
questionLabel.setEditable(false); // Make it non-editable
questionLabel.setLineWrap(true); // Enable line wrapping
questionLabel.setWrapStyleWord(true); // Wrap at word boundaries
questionLabel.setBounds(50, 50, 700, 100); // Set position and size
panel.add(questionLabel); // Add to the panel
options = new JRadioButton[4]; // Initialize the options array
group = new ButtonGroup(); // Initialize the button group
// Create radio buttons for answer options
for (int i = 0; i < 4; i++) {
options[i] = new JRadioButton(); // Create a new radio button
options[i].setFont(new Font("Arial Rounded MT Bold", Font.PLAIN, 18)); // Set font
options[i].setForeground(Color.WHITE); // Set text color
options[i].setBackground(new Color(50, 64, 113)); // Set background color
options[i].setBounds(50, 150 + i * 50, 700, 30); // Set position and size
group.add(options[i]); // Add to the button group
panel.add(options[i]); // Add to the panel
}
// Set up the Next button
nextButton = new RoundedButton("Next");
nextButton.setBounds(350, 450, 150, 50); // Set position and size
nextButton.addActionListener(e -> { // Add action listener for Next button
storeSelectedAnswer(); // Store the selected answer
if (currentQuestionIndex < questions.length - 1) {
currentQuestionIndex++; // Move to the next question
displayQuestion(); // Display the new question
} else {
calculateFinalScore(); // Calculate the final score
storeProgressInFile(username, score); // Store progress in the database
if (score >= 8) {
new congrats1(username, homePage, score); // Open the congratulations screen
} else {
new GameOver1(username); // Open the game over screen
}
dispose(); // Close the current frame
}
});
panel.add(nextButton); // Add Next button to the panel
// Set up the Previous button
previousButton = new RoundedButton("Previous");
previousButton.setBounds(130, 450, 150, 50); // Set position and size
previousButton.addActionListener(e -> { // Add action listener for Previous button
storeSelectedAnswer(); // Store the selected answer
if (currentQuestionIndex > 0) {
currentQuestionIndex--; // Move to the previous question
displayQuestion(); // Display the new question
}
});
panel.add(previousButton); // Add Previous button to the panel
displayQuestion(); // Display the first question
add(panel); // Add the main panel to the frame
setVisible(true); // Make the frame visible
}
// Method to display the current question and options
private void displayQuestion() {
questionLabel.setText("Question " + (currentQuestionIndex + 1) + ": " + questions[currentQuestionIndex]); // Update the question text
group.clearSelection(); // Clear previous selections
for (int i = 0; i < 4; i++) {
options[i].setText(optionsForQuestions[currentQuestionIndex][i]); // Set text for each option
// Check if the answer was previously selected
if (selectedAnswers[currentQuestionIndex] != null && selectedAnswers[currentQuestionIndex].equals(String.valueOf((char) ('A' + i)))) {
options[i].setSelected(true); // Select the radio button
}
}
}
// Method to store the selected answer
private void storeSelectedAnswer() {
String selectedOption = ""; // Variable to hold the selected option
for (int i = 0; i < 4; i++) {
if (options[i].isSelected()) {
selectedOption = String.valueOf((char) ('A' + i)); // Get the selected option
break; // Exit the loop once found
}
}
selectedAnswers[currentQuestionIndex] = selectedOption; // Store the selected answer
}
// Method to calculate the final score based on selected answers
private void calculateFinalScore() {
score = 0; // Reset score
for (int i = 0; i < selectedAnswers.length; i++) {
// Check if selected answer is correct
if (selectedAnswers[i] != null && selectedAnswers[i].equals(correctAnswers[i])) {
score++; // Increment score for correct answers
}
}
}
// Method to store progress in the database
private void storeProgressInFile(String username, int score) {
// Print the score and username for debugging
System.out.println(score + " " + username);
if (score >= 8) { // Check if the score is sufficient for completion
String url = "jdbc:mysql://localhost:3306/java"; // Database URL
String dbUser = "root"; // Database username
String dbPassword = "#mnta$mn$ta07.inn05/22"; // Database password
try {
// Establish a connection to the database
Connection connection = DriverManager.getConnection(url, dbUser, dbPassword);
String sql = "update users set chapter1_score =? where username = ?"; // SQL query to update score
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, score); // Set score parameter
preparedStatement.setString(2, username); // Set username parameter
int noodrecordsupdated = preparedStatement.executeUpdate(); // Execute the update
System.out.println(noodrecordsupdated); // Print number of records updated
} catch (Exception e) {
e.printStackTrace(); // Print any exceptions for debugging
}
}
}
// Main method to launch the chapter1 quiz
public static void main(String[] args) {
new chapter1("testUser", new HomePage()); // Create an instance of chapter1 with a test username
}
// Inner class for creating rounded buttons
static class RoundedButton extends JButton {
public RoundedButton(String text) {
super(text); // Call superclass constructor
setBackground(hexToColor("#fbb748")); // Set button background color
setForeground(Color.WHITE); // Set text color
setBorderPainted(false); // Disable border painting
setFocusPainted(false); // Disable focus painting
setContentAreaFilled(false); // Disable content area filling
setFont(new Font("Arial Rounded MT Bold", Font.PLAIN, 16)); // Set font
setMargin(new Insets(0, 0, 0, 0)); // Set margin to zero
setOpaque(false); // Make the button transparent
setBorder(BorderFactory.createEmptyBorder()); // Set an empty border
}
// Custom paint method to create rounded corners
protected void paintComponent(Graphics g) {
g.setColor(getBackground()); // Set background color
g.fillRoundRect(0, 0, getWidth(), getHeight(), 30, 30); // Draw rounded rectangle
super.paintComponent(g); // Call superclass paint method
}
}
// Utility method to convert hex color string to Color object
private static Color hexToColor(String hex) {
return new Color(
Integer.parseInt(hex.substring(1, 3), 16), // Red component
Integer.parseInt(hex.substring(3, 5), 16), // Green component
Integer.parseInt(hex.substring(5, 7), 16) // Blue component
);
}
}