import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.border.Border; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class QuizAssessmentApplication { private static String studentName; private static String studentID; private static JLabel studentInfoLabel; public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(() -> showWelcomeMessage()); } private static void showWelcomeMessage() { JDialog welcomeDialog = new JDialog(); welcomeDialog.setTitle("Welcome to the Quiz Assessment Application"); welcomeDialog.setSize(500, 300); welcomeDialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JPanel welcomePanel = new JPanel(); welcomePanel.setLayout(new BoxLayout(welcomePanel, BoxLayout.Y_AXIS)); welcomePanel.setBackground(Color.BLUE); JLabel welcomeLabel = new JLabel("Welcome to the Quiz Assessment Application!"); welcomeLabel.setFont(new Font("Arial", Font.BOLD, 17)); welcomeLabel.setAlignmentX(Component.CENTER_ALIGNMENT); welcomeLabel.setForeground(Color.white); JLabel infoLabel = new JLabel("Prepare for an exciting quiz experience!"); infoLabel.setFont(new Font("Arial", Font.ITALIC, 16)); infoLabel.setAlignmentX(Component.CENTER_ALIGNMENT); infoLabel.setForeground(Color.white); JButton startButton = new JButton("Start Quiz"); startButton.setAlignmentX(Component.CENTER_ALIGNMENT); startButton.setBackground(Color.blue); startButton.setForeground(Color.white); startButton.addActionListener(e -> { welcomeDialog.dispose(); createAndShowGUI(); }); studentInfoLabel = new JLabel(""); studentInfoLabel.setFont(new Font("Arial", Font.PLAIN, 14)); studentInfoLabel.setAlignmentX(Component.CENTER_ALIGNMENT); studentInfoLabel.setForeground(Color.white); welcomePanel.add(Box.createVerticalGlue()); welcomePanel.add(welcomeLabel); welcomePanel.add(Box.createRigidArea(new Dimension(0, 20))); welcomePanel.add(infoLabel); welcomePanel.add(Box.createRigidArea(new Dimension(0, 30))); welcomePanel.add(startButton); welcomePanel.add(Box.createVerticalGlue()); welcomeDialog.add(welcomePanel); welcomeDialog.setLocationRelativeTo(null); welcomeDialog.setVisible(true); } private static void createAndShowGUI() { MainLoginPanel mainLoginPanel = new MainLoginPanel(); mainLoginPanel.showMainLoginPanel(); } public static class MainLoginPanel { private JFrame mainFrame; private JPanel mainLoginPanel; public MainLoginPanel() { mainFrame = new JFrame("Login"); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainLoginPanel = new JPanel(new BorderLayout()); // Center Panel with GridBagLayout JPanel centerPanel = new JPanel(new GridBagLayout()); centerPanel.setBackground(Color.BLUE); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(10, 10, 10, 10); JLabel nameLabel = new JLabel("Enter Your Name:"); nameLabel.setFont(new Font("Arial", Font.BOLD, 17)); nameLabel.setForeground(Color.white); JLabel idLabel = new JLabel("Enter Your ID:"); idLabel.setFont(new Font("Arial", Font.BOLD, 16)); idLabel.setForeground(Color.white); JTextField nameField = new JTextField(10); JTextField idField = new JTextField(10); gbc.gridx = 0; gbc.gridy = 0; centerPanel.add(nameLabel, gbc); gbc.gridy = 1; centerPanel.add(nameField, gbc); gbc.gridy = 2; centerPanel.add(idLabel, gbc); gbc.gridy = 3; centerPanel.add(idField, gbc); gbc.gridy = 4; JButton enterBtn = new JButton("ENTER"); enterBtn.setFont(new Font("Arial", Font.BOLD, 17)); centerPanel.add(enterBtn, gbc); enterBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String enteredName = nameField.getText(); String enteredID = idField.getText(); if (!isValidName(enteredName)) { JOptionPane.showMessageDialog(mainFrame, "Please enter a valid name (alphabetical characters only).", "Error", JOptionPane.ERROR_MESSAGE); return; } if (!isValidID(enteredID)) { JOptionPane.showMessageDialog(mainFrame, "Please enter a valid ID (numeric characters only).", "Error", JOptionPane.ERROR_MESSAGE); return; } // Proceed to exams or other actions new ExamsFrame(); mainFrame.dispose(); } }); mainLoginPanel.add(centerPanel, BorderLayout.CENTER); // Bottom Panel with FlowLayout JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); buttonsPanel.setBackground(Color.BLUE); JButton exitButton = new JButton("Exit"); exitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int result = JOptionPane.showConfirmDialog(mainFrame, "Are you sure you want to exit?", "Exit Confirmation", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { System.exit(0); } } }); buttonsPanel.add(exitButton); mainLoginPanel.add(buttonsPanel, BorderLayout.SOUTH); } public void showMainLoginPanel() { mainFrame.getContentPane().add(mainLoginPanel); mainFrame.setSize(600, 300); mainFrame.setLocationRelativeTo(null); mainFrame.setVisible(true); } // Add these helper methods to validate name and ID private boolean isValidName(String name) { return name.matches("[a-zA-Z]+"); } private boolean isValidID(String id) { return id.matches("\\d+"); } } public static class ExamsFrame extends JFrame { public ExamsFrame() { setTitle("Dash Board"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); JPanel examsPanel = new JPanel(new GridBagLayout()); examsPanel.setBackground(Color.BLUE); examsPanel.setBorder(new EmptyBorder(10, 10, 10, 10)); JButton exam1Button = new JButton("Exam 1"); JButton exam2Button = new JButton("Exam 2"); JButton exam3Button = new JButton("Exam 3"); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(20, 20, 20, 25); gbc.gridx = 0; gbc.gridy = 0; JLabel titleLabel = new JLabel("Choose an Exam:"); titleLabel.setFont(new Font("Arial", Font.BOLD, 30)); titleLabel.setForeground(Color.white); examsPanel.add(titleLabel, gbc); gbc.gridy = 1; examsPanel.add(exam1Button, gbc); gbc.gridy = 2; examsPanel.add(exam2Button, gbc); gbc.gridy = 3; examsPanel.add(exam3Button, gbc); exam1Button.addActionListener(e -> startExam("Exam 1", 5, 25, 1 * 60)); exam2Button.addActionListener(e -> startExam("Exam 2", 5, 25, 1 * 60)); exam3Button.addActionListener(e -> startExam("Exam 3", 5, 25, 1 * 60)); add(examsPanel, BorderLayout.CENTER); JPanel resultsPanel = new JPanel(new GridLayout(3, 1)); resultsPanel.setBackground(Color.WHITE); // Border Border resultsPanelBorder = BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(Color.BLACK, 3), BorderFactory.createEmptyBorder(5, 5, 5, 5)); resultsPanel.setBorder(resultsPanelBorder); resultsPanel.setSize(80, 200); resultsPanel.add(new JLabel("Exam 1 : ")); resultsPanel.add(new JLabel("Exam 2 : ")); resultsPanel.add(new JLabel("Exam 3 : ")); add(resultsPanel, BorderLayout.EAST); JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); buttonsPanel.setBackground(Color.BLUE); JButton logoutButton = new JButton("Logout"); logoutButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int result = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?", "Exit Confirmation", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { dispose(); new MainLoginPanel().showMainLoginPanel(); } } }); buttonsPanel.add(logoutButton); add(buttonsPanel, BorderLayout.SOUTH); setSize(600, 300); setLocationRelativeTo(null); setVisible(true); } private void startExam(String examName, int numQuestions, int pointsPerQuestion, int examDurationInSeconds) { JFrame examFrame = new JFrame(examName); examFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); ExamPanel examPanel = new ExamPanel(numQuestions, pointsPerQuestion, examDurationInSeconds, examFrame); examPanel.generateCountryQuestions(); examFrame.getContentPane().add(examPanel, BorderLayout.CENTER); examFrame.setSize(500, 300); examFrame.setLocationRelativeTo(null); examFrame.setVisible(true); } } public static class ExamPanel extends JPanel { private int totalMarks; private int numQuestions; private Timer timer; private int examDurationInSeconds; private JFrame parentFrame; private JLabel timerLabel; public ExamPanel(int numQuestions, int pointsPerQuestion, int examDurationInSeconds, JFrame parentFrame) { this.numQuestions = numQuestions; totalMarks = 0; this.examDurationInSeconds = examDurationInSeconds; this.parentFrame = parentFrame; setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); JButton submitButton = new JButton("Submit Exam"); timerLabel = new JLabel(formatTime(examDurationInSeconds)); add(submitButton); add(timerLabel); submitButton.addActionListener(e -> submitExam()); timer = new Timer(1000, new TimerListener()); timer.setInitialDelay(0); timer.start(); } public class TimerListener implements ActionListener { public int remainingTime = examDurationInSeconds; @Override public void actionPerformed(ActionEvent e) { if (remainingTime > 0) { remainingTime--; timerLabel.setText(formatTime(remainingTime)); } else { submitExam(); } } } public class Question { private String question; private List<String> options; public Question(String question, List<String> options) { this.question = question; this.options = options; } public String getQuestion() { return question; } public List<String> getOptions() { return options; } } // ... public void generateCountryQuestions() { for (int i = 1; i <= numQuestions; i++) { Question questionAndOptions = generateCountryQuestion(); String question = questionAndOptions.getQuestion(); List<String> options = questionAndOptions.getOptions(); add(new JLabel(question)); ButtonGroup buttonGroup = new ButtonGroup(); for (String option : options) { JRadioButton radioButton = new JRadioButton(option); buttonGroup.add(radioButton); add(radioButton); } } } private Question generateCountryQuestion() { String[] countries = {"France", "Germany", "Spain", "Italy", "Austria", "Belarus", "Brazil","Egypt","Greece", "Japan"}; String[] capitals = {"Paris", "Berlin", "Madrid", "Rome", "Vienna", "Minsk", " Brasilia","Cairo","Athens", "Tokyo"}; List<String> optionsList = new ArrayList<>(); // Select a random country int randomIndex = (int) (Math.random() * countries.length); String selectedCountry = countries[randomIndex]; String correctCapital = capitals[randomIndex]; // Create the question String question = "What is the capital of " + selectedCountry + "?"; // Create options (including the correct capital and three other random capitals) optionsList.add(correctCapital); while (optionsList.size() < 4) { int randomOptionIndex = (int) (Math.random() * capitals.length); String randomCapital = capitals[randomOptionIndex]; if (!optionsList.contains(randomCapital)) { optionsList.add(randomCapital); } } Collections.shuffle(optionsList); return new Question(question, optionsList); } private int evaluateCountryAnswers() { int correctAnswers = 0; // Loop through the options and check for correct answers Component[] components = getComponents(); String correctCapital = getCorrectCountryCapital(); // Get the correct capital for the current question for (Component component : components) { if (component instanceof JRadioButton) { JRadioButton radioButton = (JRadioButton) component; if (radioButton.isSelected() && isCorrectCountryAnswer(radioButton.getText(), correctCapital)) { // Add 25 marks for each correct answer correctAnswers++; } } } return correctAnswers; } private boolean isCorrectCountryAnswer(String selectedOption, String correctCapital) { return selectedOption.equals(correctCapital); } private String getCorrectCountryCapital() { String[] capitals = {"Paris", "Berlin", "Madrid", "Rome", "Vienna","Minsk", "Brasilia","Cairo","Athens","Tokyo"}; int randomIndex = (int) (Math.random() * capitals.length); return capitals[randomIndex]; } public void submitExam() { timer.stop(); int correctAnswers = evaluateCountryAnswers(); int final_mark = correctAnswers * 25; String grade; if (final_mark >= 90) { grade = "A"; } else if (final_mark >= 80) { grade = "B"; } else if (final_mark >= 70) { grade = "C"; } else if (final_mark >= 60) { grade = "D"; } else { grade = "F"; } JOptionPane.showMessageDialog(this, "Your total marks: " + final_mark + "/100\nYour grade: " + grade, "Exam Result", JOptionPane.INFORMATION_MESSAGE); parentFrame.dispose(); } private String formatTime(int seconds) { int minutes = seconds / 60; int remainingSeconds = seconds % 60; return String.format("%02d:%02d", minutes, remainingSeconds); } } } public class Main { public static void main(String[] args) { System.setProperty("java.awt.headless", "true"); // your code here } }
Write, Run & Share Java code online using OneCompiler's Java online compiler for free. It's one of the robust, feature-rich online compilers for Java language, running the Java LTS version 17. Getting started with the OneCompiler's Java editor is easy and fast. The editor shows sample boilerplate code when you choose language as Java and start coding.
OneCompiler's Java online editor supports stdin and users can give inputs to the programs using the STDIN textbox under the I/O tab. Using Scanner class in Java program, you can read the inputs. Following is a sample program that shows reading STDIN ( A string in this case ).
import java.util.Scanner;
class Input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your name: ");
String inp = input.next();
System.out.println("Hello, " + inp);
}
}
OneCompiler supports Gradle for dependency management. Users can add dependencies in the build.gradle
file and use them in their programs. When you add the dependencies for the first time, the first run might be a little slow as we download the dependencies, but the subsequent runs will be faster. Following sample Gradle configuration shows how to add dependencies
apply plugin:'application'
mainClassName = 'HelloWorld'
run { standardInput = System.in }
sourceSets { main { java { srcDir './' } } }
repositories {
jcenter()
}
dependencies {
// add dependencies here as below
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
}
Java is a very popular general-purpose programming language, it is class-based and object-oriented. Java was developed by James Gosling at Sun Microsystems ( later acquired by Oracle) the initial release of Java was in 1995. Java 17 is the latest long-term supported version (LTS). As of today, Java is the world's number one server programming language with a 12 million developer community, 5 million students studying worldwide and it's #1 choice for the cloud development.
short x = 999; // -32768 to 32767
int x = 99999; // -2147483648 to 2147483647
long x = 99999999999L; // -9223372036854775808 to 9223372036854775807
float x = 1.2;
double x = 99.99d;
byte x = 99; // -128 to 127
char x = 'A';
boolean x = true;
When ever you want to perform a set of operations based on a condition If-Else is used.
if(conditional-expression) {
// code
} else {
// code
}
Example:
int i = 10;
if(i % 2 == 0) {
System.out.println("i is even number");
} else {
System.out.println("i is odd number");
}
Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.
switch(<conditional-expression>) {
case value1:
// code
break; // optional
case value2:
// code
break; // optional
...
default:
//code to be executed when all the above cases are not matched;
}
For loop is used to iterate a set of statements based on a condition. Usually for loop is preferred when number of iterations is known in advance.
for(Initialization; Condition; Increment/decrement){
//code
}
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while(<condition>){
// code
}
Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.
do {
// code
} while (<condition>);
Class is the blueprint of an object, which is also referred as user-defined data type with variables and functions. Object is a basic unit in OOP, and is an instance of the class.
class
keyword is required to create a class.
class Mobile {
public: // access specifier which specifies that accessibility of class members
string name; // string variable (attribute)
int price; // int variable (attribute)
};
Mobile m1 = new Mobile();
public class Greeting {
static void hello() {
System.out.println("Hello.. Happy learning!");
}
public static void main(String[] args) {
hello();
}
}
Collection is a group of objects which can be represented as a single unit. Collections are introduced to bring a unified common interface to all the objects.
Collection Framework was introduced since JDK 1.2 which is used to represent and manage Collections and it contains:
This framework also defines map interfaces and several classes in addition to Collections.
Collection | Description |
---|---|
Set | Set is a collection of elements which can not contain duplicate values. Set is implemented in HashSets, LinkedHashSets, TreeSet etc |
List | List is a ordered collection of elements which can have duplicates. Lists are classified into ArrayList, LinkedList, Vectors |
Queue | FIFO approach, while instantiating Queue interface you can either choose LinkedList or PriorityQueue. |
Deque | Deque(Double Ended Queue) is used to add or remove elements from both the ends of the Queue(both head and tail) |
Map | Map contains key-values pairs which don't have any duplicates. Map is implemented in HashMap, TreeMap etc. |