-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask2 -Grade Calculator.java
More file actions
79 lines (67 loc) · 2.4 KB
/
task2 -Grade Calculator.java
File metadata and controls
79 lines (67 loc) · 2.4 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
import javax.swing.*;
import java.awt.event.*;
public class GradeCalculator extends JFrame implements ActionListener {
JLabel[] labels;
JTextField[] textFields;
JButton calculateButton;
public GradeCalculator() {
labels = new JLabel[5];
textFields = new JTextField[5];
String[] subjects = {"Subject 1", "Subject 2", "Subject 3", "Subject 4", "Subject 5"};
for (int i = 0; i < 5; i++) {
labels[i] = new JLabel(subjects[i]);
textFields[i] = new JTextField();
labels[i].setBounds(50, 50 + i * 50, 100, 30);
textFields[i].setBounds(160, 50 + i * 50, 100, 30);
add(labels[i]);
add(textFields[i]);
}
calculateButton = new JButton("Calculate");
calculateButton.setBounds(100, 300, 100, 30);
calculateButton.addActionListener(this);
add(calculateButton);
setTitle("Student Grade Calculator");
setSize(300, 400);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == calculateButton) {
int totalMarks = 0;
int numSubjects = 0;
for (int i = 0; i < 5; i++) {
String marksText = textFields[i].getText();
if (!marksText.isEmpty()) {
int marks = Integer.parseInt(marksText);
totalMarks += marks;
numSubjects++;
}
}
double averagePercentage = (double) totalMarks / (numSubjects * 100) * 100;
String grade = calculateGrade(averagePercentage);
JOptionPane.showMessageDialog(this, "Total Marks: " + totalMarks +
"\nAverage Percentage: " + averagePercentage + "%" +
"\nGrade: " + grade);
}
}
private String calculateGrade(double percentage) {
if (percentage >= 90) {
return "A+";
} else if (percentage >= 80) {
return "A";
} else if (percentage >= 70) {
return "B";
} else if (percentage >= 60) {
return "C";
} else if (percentage >= 50) {
return "D";
} else {
return "F";
}
}
public static void main(String[] args) {
new GradeCalculator();
}
}