0% found this document useful (0 votes)
29 views26 pages

Week 12

The document provides a comprehensive overview of Java programming concepts, including how to manipulate Vectors and HashSets, the differences between Comparable and Comparator interfaces, and the use of Iterators. It includes practical examples such as sorting Player objects, creating a student registration system using GUI, and implementing a simple calculator. Additionally, it discusses event handling and provides sample code for various applications, showcasing the use of Swing components and data structures.

Uploaded by

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

Week 12

The document provides a comprehensive overview of Java programming concepts, including how to manipulate Vectors and HashSets, the differences between Comparable and Comparator interfaces, and the use of Iterators. It includes practical examples such as sorting Player objects, creating a student registration system using GUI, and implementing a simple calculator. Additionally, it discusses event handling and provides sample code for various applications, showcasing the use of Swing components and data structures.

Uploaded by

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

1.How do you add an element to a Vector in java?

To add an element to a Vector in Java, you simply use the add() method, passing
the element you want to add as its argument. For example:

Vector<String> vector = new Vector<>();

vector.add("Element");

2. What is primary characteristic of Hashset in Java?

The primary characteristic of a HashSet in Java is that it does not allow duplicate
elements. When you attempt to add a duplicate element to a HashSet, it simply
ignores the addition, maintaining a collection of unique elements only.

3.Differentiate comparable and comparator?

Comparable is an interface used for objects to implement natural ordering via


the compareTo() method, enabling them to be sorted automatically. Comparator,
another interface, provides a way to define custom sorting logic externally for
objects that don't implement Comparable or when alternative sorting orders are
needed. It allows sorting objects based on criteria other than their natural
ordering.

4.Which method is used with Iterator to retrieve next elements from a collection?

The method used with Iterator to retrieve the next elements from a collection is
next(). When you call iterator.next(), it returns the next element in the
collection and advances the iterator's position to the subsequent element.

5.Which package is commonly used for implementing event handling.

In Java, the java.awt.event package is commonly used for implementing event


handling. This package provides classes and interfaces for handling events
generated by user interactions with graphical user interface (GUI) components in
Abstract Window Toolkit (AWT) and Swing.

In-lab: 1. The Player class is provided for you in your editor. It has 2 fields: a String and a integer.
Given an array of n Player objects, write a comparator that sorts them in order of decreasing score; if
2 or more players have the same score, sort those players alphabetically by name. To do this, you
must create a Checker class that implements the Comparator interface, then write an
intcompare(Player a, Player b) method implementing the Comparator. Compare (T o1, T o2) method.
class Checker
{

Comparator<Player> desc=new Comparator<Player>() {

@Override
public int compare(Player a, Player b) {

if(a.score==b.score)
{
if(a.name.compareTo(b.name)>0)
return -1;
if(a.name.compareTo(b.name)<0)
return 1;
return 0;
}
if(a.score>b.score)
return -1;
if(a.score<b.score)
return 1;
return 0;
}

};

}
Sample Input

5
amy 100
david 100
heraldo 50
aakansha 75
aleksa 150
Sample Output

aleksa 150
amy 100
david 100
aakansha 75
heraldo 50

2. You are the class representative and are required to store the Student Details and ID numbers of
all your classmates. Develop a program which takes in the details of the students as dynamic user
input and store them in Vector. It should print the details and it should also be able to help you
search for a student detail using the ID number.

import java.util.Scanner;
import java.util.Vector;

class Student {
private String name;
private int id;

public Student(String name, int id) {


this.name = name;
this.id = id;
}

public String getName() {


return name;
}

public int getId() {


return id;
}

@Override
public String toString() {
return "Name: " + name + ", ID: " + id;
}
}

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Vector<Student> students = new Vector<>();
// Input student details
while (true) {
System.out.println("Enter student name (type 'exit' to stop):");
String name = scanner.nextLine();
if (name.equals("exit")) {
break;
}
System.out.println("Enter student ID:");
int id = scanner.nextInt();
scanner.nextLine(); // Consume newline
students.add(new Student(name, id));
}

// Print student details


System.out.println("\nStudent details:");
for (Student student : students) {
System.out.println(student);
}

// Search by ID
System.out.println("\nEnter ID to search for a student:");
int searchId = scanner.nextInt();
scanner.nextLine(); // Consume newline
boolean found = false;
for (Student student : students) {
if (student.getId() == searchId) {
System.out.println("Student found: " + student);
found = true;
break;
}
}
if (!found) {
System.out.println("Student with ID " + searchId + " not found.");
}
}
}

Enter student name (type 'exit' to stop):


John
Enter student ID:
123
Enter student name (type 'exit' to stop):
Alice
Enter student ID:
456
Enter student name (type 'exit' to stop):
exit

Student details:
Name: John, ID: 123
Name: Alice, ID: 456

Enter ID to search for a student:


456
Student found: Name: Alice, ID: 456
3. Develop a simple calculator to perform basic operations on 2 integers using GUI.

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class SimpleCalculator extends JFrame implements ActionListener {

private JTextField numField1, numField2, resultField;

private JButton addButton, subButton, mulButton, divButton;

public SimpleCalculator() {

setTitle("Simple Calculator");

setSize(300, 200);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

// Creating input fields

numField1 = new JTextField(10);

numField2 = new JTextField(10);

resultField = new JTextField(10);

resultField.setEditable(false);

// Creating buttons

addButton = new JButton("+");

subButton = new JButton("-");

mulButton = new JButton("*");

divButton = new JButton("/");

// Adding action listeners

addButton.addActionListener(this);

subButton.addActionListener(this);

mulButton.addActionListener(this);

divButton.addActionListener(this);

// Creating panel for buttons

JPanel buttonPanel = new JPanel();

buttonPanel.add(addButton);

buttonPanel.add(subButton);

buttonPanel.add(mulButton);

buttonPanel.add(divButton);

// Creating main panel

JPanel mainPanel = new JPanel(new GridLayout(4, 2));

mainPanel.add(new JLabel("Number 1: "));

mainPanel.add(numField1);
mainPanel.add(new JLabel("Number 2: "));

mainPanel.add(numField2);

mainPanel.add(new JLabel("Result: "));

mainPanel.add(resultField);

mainPanel.add(new JLabel()); // Empty label for spacing

mainPanel.add(buttonPanel);

// Adding main panel to frame

add(mainPanel);

setVisible(true);

@Override

public void actionPerformed(ActionEvent e) {

int num1 = Integer.parseInt(numField1.getText());

int num2 = Integer.parseInt(numField2.getText());

int result = 0;

if (e.getSource() == addButton) {

result = num1 + num2;

} else if (e.getSource() == subButton) {

result = num1 - num2;

} else if (e.getSource() == mulButton) {

result = num1 * num2;

} else if (e.getSource() == divButton) {

if (num2 != 0) {

result = num1 / num2;

} else {

JOptionPane.showMessageDialog(this, "Cannot divide by zero!", "Error",


JOptionPane.ERROR_MESSAGE);
return;

resultField.setText(Integer.toString(result));

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {

new SimpleCalculator();

});

PostLab

1.Write a java program that reads Student ID, Name, age, gender and prints the details on User
Interface. (Hint: Use JOptionPane of javax.swing package

import javax.swing.JOptionPane;

public class StudentDetailsGUI {

public static void main(String[] args) {

// Read student details

String idStr = JOptionPane.showInputDialog("Enter Student ID:");

int id = Integer.parseInt(idStr);

String name = JOptionPane.showInputDialog("Enter Student Name:");


String ageStr = JOptionPane.showInputDialog("Enter Student Age:");

int age = Integer.parseInt(ageStr);

String gender = JOptionPane.showInputDialog("Enter Student Gender:");

// Construct details message

StringBuilder message = new StringBuilder();

message.append("Student Details:\n");

message.append("ID: ").append(id).append("\n");

message.append("Name: ").append(name).append("\n");

message.append("Age: ").append(age).append("\n");

message.append("Gender: ").append(gender);

// Display details using JOptionPane

JOptionPane.showMessageDialog(null, message.toString(), "Student Details",


JOptionPane.INFORMATION_MESSAGE);

2.Develop a java program using swing package. The program must display a student registration
page, which reads ID, Name, Gender (Use Radio Buttons) and department (Use Drop down selection)
and two buttons Submit and Reset. When the user clicks Submit, then validate the data, use
JOptionPane to alert if any data is missing or entered wrong, otherwise display the data submitted
back on JOptionPane. The reset button clears all the data

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class StudentRegistrationPage extends JFrame implements ActionListener {

private JTextField idField, nameField;

private JRadioButton maleRadio, femaleRadio;


private ButtonGroup genderGroup;

private JComboBox<String> departmentDropdown;

private JButton submitButton, resetButton;

public StudentRegistrationPage() {

setTitle("Student Registration");

setSize(300, 250);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLocationRelativeTo(null);

// Initialize components

idField = new JTextField(10);

nameField = new JTextField(10);

maleRadio = new JRadioButton("Male");

femaleRadio = new JRadioButton("Female");

genderGroup = new ButtonGroup();

genderGroup.add(maleRadio);

genderGroup.add(femaleRadio);

departmentDropdown = new JComboBox<>(new String[]{"Computer Science", "Electrical


Engineering", "Mechanical Engineering"});

submitButton = new JButton("Submit");

resetButton = new JButton("Reset");

// Add action listeners

submitButton.addActionListener(this);

resetButton.addActionListener(this);

// Create panel for student details

JPanel detailsPanel = new JPanel(new GridLayout(5, 2));

detailsPanel.add(new JLabel("ID:"));

detailsPanel.add(idField);
detailsPanel.add(new JLabel("Name:"));

detailsPanel.add(nameField);

detailsPanel.add(new JLabel("Gender:"));

detailsPanel.add(maleRadio);

detailsPanel.add(new JLabel(""));

detailsPanel.add(femaleRadio);

detailsPanel.add(new JLabel("Department:"));

detailsPanel.add(departmentDropdown);

// Create panel for buttons

JPanel buttonPanel = new JPanel();

buttonPanel.add(submitButton);

buttonPanel.add(resetButton);

// Add panels to frame

getContentPane().setLayout(new BorderLayout());

getContentPane().add(detailsPanel, BorderLayout.CENTER);

getContentPane().add(buttonPanel, BorderLayout.SOUTH);

setVisible(true);

@Override

public void actionPerformed(ActionEvent e) {

if (e.getSource() == submitButton) {

if (idField.getText().isEmpty() || nameField.getText().isEmpty() || (!maleRadio.isSelected()


&& !femaleRadio.isSelected())) {

JOptionPane.showMessageDialog(this, "Please fill in all fields.", "Error",


JOptionPane.ERROR_MESSAGE);

} else {

String gender = maleRadio.isSelected() ? "Male" : "Female";

String department = (String) departmentDropdown.getSelectedItem();


String message = "ID: " + idField.getText() + "\nName: " + nameField.getText() + "\nGender:
" + gender + "\nDepartment: " + department;

JOptionPane.showMessageDialog(this, message, "Registration Successful",


JOptionPane.INFORMATION_MESSAGE);

} else if (e.getSource() == resetButton) {

idField.setText("");

nameField.setText("");

genderGroup.clearSelection();

departmentDropdown.setSelectedIndex(0);

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {

new StudentRegistrationPage();

});

}
3. Find the town Judge: In a town there are n people labelled from 1 to n. There is a rumour that one
of these people is secretly the town judge. If the town judge exists, then: 1. The town judge trusts
nobody. 2. Everybody (except for the town judge) trusts the town judge. 3. There is exactly one
person that satisfies properties 1 and 2. You are given an

class Solution {
public int findJudge(int n, int[][] trust) {
int m = trust.length;
int indegree[] = new int[n + 1];
for(int i = 0; i < m; i++){
indegree[trust[i][1]]++;
}

int answer = 0;

for(int i = 1; i <= n; i++){


if(indegree[i] == n - 1){
answer = i;
}
}

for(int i = 0; i < m; i++){


if(trust[i][0] == answer){
return -1;
}
}

return answer == 0 ? -1 : answer;

}
}

Skill Session

1.Madhuri wants to develop an app which sorts the Student Ids based on marks(ascending) if marks
are equal sort as per their student ID. The User provides the marks of different students along with
student Ids and stores them in a Vector. Help her out writing the program to develop the app. (Use
comparator interface)

import java.util.*;

class Student {

private int id;

private int marks;

public Student(int id, int marks) {

this.id = id;

this.marks = marks;

}
public int getId() {

return id;

public int getMarks() {

return marks;

class StudentComparator implements Comparator<Student> {

@Override

public int compare(Student s1, Student s2) {

// Compare based on marks

if (s1.getMarks() != s2.getMarks()) {

return s1.getMarks() - s2.getMarks();

} else {

// If marks are equal, compare based on student ID

return s1.getId() - s2.getId();

public class SortStudentIds {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

Vector<Student> students = new Vector<>();

// Input student details

while (true) {

System.out.println("Enter student ID (or type 'exit' to stop):");


String input = scanner.nextLine();

if (input.equals("exit")) {

break;

int id = Integer.parseInt(input);

System.out.println("Enter student marks:");

int marks = scanner.nextInt();

scanner.nextLine(); // Consume newline

students.add(new Student(id, marks));

// Sort students based on marks and ID

Collections.sort(students, new StudentComparator());

// Print sorted student IDs

System.out.println("\nSorted student IDs based on marks (ascending):");

for (Student student : students) {

System.out.println("ID: " + student.getId() + ", Marks: " + student.getMarks());

Output

Enter student ID (or type 'exit' to stop):

101

Enter student marks:

80

Enter student ID (or type 'exit' to stop):

102

Enter student marks:

75

Enter student ID (or type 'exit' to stop):


103

Enter student marks:

80

Enter student ID (or type 'exit' to stop):

104

Enter student marks:

85

Enter student ID (or type 'exit' to stop):

exit

Sorted student IDs based on marks (ascending):

ID: 102, Marks: 75

ID: 101, Marks: 80

ID: 103, Marks: 80

ID: 104, Marks: 85

2. Develop a student registration form that takes Student ID, name, DOB, Email, and mobile number
using swing components

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class StudentRegistrationForm extends JFrame {


private JTextField idField, nameField, dobField, emailField, mobileField;
private JButton submitButton, resetButton;

public StudentRegistrationForm() {
setTitle("Student Registration Form");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// Initialize components
idField = new JTextField(20);
nameField = new JTextField(20);
dobField = new JTextField(20);
emailField = new JTextField(20);
mobileField = new JTextField(20);
submitButton = new JButton("Submit");
resetButton = new JButton("Reset");

// Add action listeners


submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
submit();
}
});
resetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
reset();
}
});

// Create panel for form fields


JPanel formPanel = new JPanel(new GridLayout(5, 2));
formPanel.add(new JLabel("Student ID:"));
formPanel.add(idField);
formPanel.add(new JLabel("Name:"));
formPanel.add(nameField);
formPanel.add(new JLabel("DOB (YYYY-MM-DD):"));
formPanel.add(dobField);
formPanel.add(new JLabel("Email:"));
formPanel.add(emailField);
formPanel.add(new JLabel("Mobile Number:"));
formPanel.add(mobileField);

// Create panel for buttons


JPanel buttonPanel = new JPanel();
buttonPanel.add(submitButton);
buttonPanel.add(resetButton);

// Add panels to frame


getContentPane().setLayout(new BorderLayout());
getContentPane().add(formPanel, BorderLayout.CENTER);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);

setVisible(true);
}

private void submit() {


// Validate input
String id = idField.getText().trim();
String name = nameField.getText().trim();
String dob = dobField.getText().trim();
String email = emailField.getText().trim();
String mobile = mobileField.getText().trim();

if (id.isEmpty() || name.isEmpty() || dob.isEmpty() || email.isEmpty() ||


mobile.isEmpty()) {
JOptionPane.showMessageDialog(this, "Please fill in all fields.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
// Process data (e.g., save to database)
// In this example, we just display the data
StringBuilder message = new StringBuilder();
message.append("Student ID: ").append(id).append("\n");
message.append("Name: ").append(name).append("\n");
message.append("DOB: ").append(dob).append("\n");
message.append("Email: ").append(email).append("\n");
message.append("Mobile Number: ").append(mobile);

JOptionPane.showMessageDialog(this, message.toString(), "Registration


Successful", JOptionPane.INFORMATION_MESSAGE);
}

private void reset() {


idField.setText("");
nameField.setText("");
dobField.setText("");
emailField.setText("");
mobileField.setText("");
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new StudentRegistrationForm();
}
});
}
}
3. Rakesh is participating in a Hackathon, and it requires him to make a Login page. Help him out by
writing a program to create the page. It should look as follows:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class LoginPage extends JFrame implements ActionListener {


private JTextField usernameField;
private JPasswordField passwordField;
private JButton submitButton;

public LoginPage() {
setTitle("Login Page");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

// Initialize components
usernameField = new JTextField(15);
passwordField = new JPasswordField(15);
submitButton = new JButton("Submit");

// Add action listener to the submit button


submitButton.addActionListener(this);
// Create panel for login form
JPanel loginPanel = new JPanel(new GridLayout(3, 2));
loginPanel.add(new JLabel("Username:"));
loginPanel.add(usernameField);
loginPanel.add(new JLabel("Password:"));
loginPanel.add(passwordField);
loginPanel.add(new JLabel()); // Empty label for spacing
loginPanel.add(submitButton);

// Add login panel to frame


getContentPane().add(loginPanel, BorderLayout.CENTER);

setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
// Get username and password from input fields
String username = usernameField.getText();
String password = new String(passwordField.getPassword());

// Perform login authentication (e.g., check against database)


// In this example, we simply check if username and password are not
empty
if (!username.isEmpty() && !password.isEmpty()) {
JOptionPane.showMessageDialog(this, "Login Successful!", "Success",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(this, "Please enter username and
password.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new LoginPage();
}
});
}
}
4. Given an array of N Player objects, write a comparator that sorts them in order of decreasing
score; if 2 or more players have the same score, sort those players alphabetically by name. To do this,
you must create a Checker class that implements the Comparator interface, then write an int
compare (Player a, Player b) method implementing the Comparator.compare (T o1, T o2) method.

class Checker
{

Comparator<Player> desc=new Comparator<Player>() {

@Override
public int compare(Player a, Player b) {

if(a.score==b.score)
{
if(a.name.compareTo(b.name)>0)
return -1;
if(a.name.compareTo(b.name)<0)
return 1;
return 0;
}
if(a.score>b.score)
return -1;
if(a.score<b.score)
return 1;
return 0;
}

};

Output

Sorted Players:

John 100

Alice 90

Alice 90

Charlie 85

Bob 80
5. Create a comparator and use it to sort an array
import java.util.*;

class Checker implements Comparator<Player>{

public int compare(Player a, Player b) {


// If 2 Players have the same score
if(a.score == b.score){
// Order alphabetically by name
return a.name.compareTo(b.name);
}

// Otherwise, order higher score first


return ((Integer) b.score).compareTo(a.score);
}
}

Sample Input

5
amy 100
david 100
heraldo 50
aakansha 75
aleksa 150
Sample Output

aleksa 150
amy 100
david 100
aakansha 75
heraldo 50

You might also like