0% found this document useful (0 votes)
2 views20 pages

java 1-9

The document contains multiple Java programs demonstrating different functionalities. It includes a student information application that computes CGPA, a shopping application that calculates total costs with discounts, a program to count substring occurrences and check for anagrams, a generic stack implementation, and a phone system for managing missed calls. Each program is structured with appropriate classes, methods, and user interactions.

Uploaded by

sandeepswamy54
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)
2 views20 pages

java 1-9

The document contains multiple Java programs demonstrating different functionalities. It includes a student information application that computes CGPA, a shopping application that calculates total costs with discounts, a program to count substring occurrences and check for anagrams, a generic stack implementation, and a phone system for managing missed calls. Each program is structured with appropriate classes, methods, and user interactions.

Uploaded by

sandeepswamy54
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/ 20

Prog 6

package swingdemo;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
public class StudentInfoApp extends JFrame implements ActionListener {
private JTextField nameField, usnField, ageField, addressField, sgpa1Field, sgpa2Field,
sgpa3Field, sgpa4Field, categoryField;
private JButton computeButton, doneButton, displayButton;
private JTextArea displayArea;
private ArrayList<Student> studentList;
public StudentInfoApp() {
studentList = new ArrayList<>();

setTitle("Student Information");
setLayout(new GridLayout(12, 2));
add(new JLabel("Name:"));
nameField = new JTextField();
add(nameField);
add(new JLabel("USN:"));
usnField = new JTextField();
add(usnField);
add(new JLabel("Age:"));
ageField = new JTextField();
add(ageField);
add(new JLabel("Address:"));
addressField = new JTextField();
add(addressField);
add(new JLabel("SGPA 1:"));
sgpa1Field = new JTextField();
add(sgpa1Field);
add(new JLabel("SGPA 2:"));
sgpa2Field = new JTextField();
add(sgpa2Field);
add(new JLabel("SGPA 3:"));
sgpa3Field = new JTextField();
add(sgpa3Field);
add(new JLabel("SGPA 4:"));
sgpa4Field = new JTextField();
add(sgpa4Field);
add(new JLabel("Category:"));
categoryField = new JTextField();
add(categoryField);
computeButton = new JButton("Compute");
computeButton.addActionListener(this);
add(computeButton);
doneButton = new JButton("Done");
doneButton.addActionListener(this);
add(doneButton);
displayButton = new JButton("Display");
displayButton.addActionListener(this);
add(displayButton);
displayArea = new JTextArea();
add(new JScrollPane(displayArea));

setSize(400, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == computeButton) {
computeCGPA();
} else if (e.getSource() == doneButton) {
addStudent();
} else if (e.getSource() == displayButton) {
displayStudents();
}
}
private void computeCGPA() {
try {
double sgpa1 = Double.parseDouble(sgpa1Field.getText());
double sgpa2 = Double.parseDouble(sgpa2Field.getText());
double sgpa3 = Double.parseDouble(sgpa3Field.getText());
double sgpa4 = Double.parseDouble(sgpa4Field.getText());
double cgpa = (sgpa1 + sgpa2 + sgpa3 + sgpa4) / 4.0;
JOptionPane.showMessageDialog(this, "CGPA: " + cgpa);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "Please enter valid SGPA values.");
}
}
private void addStudent() {
String name = nameField.getText();
String usn = usnField.getText();
String ageText = ageField.getText();
String address = addressField.getText();
String category = categoryField.getText();
if (name.isEmpty() || usn.isEmpty() || ageText.isEmpty() || address.isEmpty() ||
category.isEmpty()) {
JOptionPane.showMessageDialog(this, "All fields must be filled out.");
return;
}
try {
int age = Integer.parseInt(ageText);
double sgpa1 = Double.parseDouble(sgpa1Field.getText());
double sgpa2 = Double.parseDouble(sgpa2Field.getText());
double sgpa3 = Double.parseDouble(sgpa3Field.getText());
double sgpa4 = Double.parseDouble(sgpa4Field.getText());
Student student = new Student(name, usn, age, address, sgpa1, sgpa2, sgpa3, sgpa4,
category);
studentList.add(student);
JOptionPane.showMessageDialog(this, "Student details added.");
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "Please enter valid numerical values for age and
SGPA.");
}
}
private void displayStudents() {
StringBuilder displayText = new StringBuilder();
for (Student student : studentList) {
displayText.append(student).append("\n");
}
displayArea.setText(displayText.toString());
}
public static void main(String[] args) {
new StudentInfoApp();
}
}
class Student {
private String name, usn, address, category;
private int age;
private double sgpa1, sgpa2, sgpa3, sgpa4;
public Student(String name, String usn, int age, String address, double sgpa1, double sgpa2,
double sgpa3, double sgpa4, String category) {
this.name = name;
this.usn = usn;
this.age = age;
this.address = address;
this.sgpa1 = sgpa1;
this.sgpa2 = sgpa2;
this.sgpa3 = sgpa3;
this.sgpa4 = sgpa4;
this.category = category;
}
@Override
public String toString() {
return "Name: " + name + ", USN: " + usn + ", Age: " + age + ", Address: " + address + ", SGPA1:
" + sgpa1 + ", SGPA2: " + sgpa2 + ", SGPA3: " + sgpa3 + ", SGPA4: " + sgpa4 + ", Category: " +
category;
}
}

Prog 7
package PROG7;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
public class ShoppingApp extends JFrame {
private JTextField itemIdField, quantityField;
private JLabel itemNameLabel, totalCostLabel;
private JButton calculateButton, printButton;
// Sample item data
private HashMap<String, String> itemNames = new HashMap<>();
private HashMap<String, Double> itemPrices = new HashMap<>();
public ShoppingApp() {
// Initialize sample item data
itemNames.put("101", "Apple");
itemPrices.put("101", 0.5);
itemNames.put("102", "Banana");
itemPrices.put("102", 0.2);
itemNames.put("103", "Orange");
itemPrices.put("103", 0.3);
// Set up the frame
setTitle("Shopping Application");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(6, 2));
// Create components
JLabel itemIdLabel = new JLabel("Item ID:");
itemIdField = new JTextField();
JLabel quantityLabel = new JLabel("Quantity:");
quantityField = new JTextField();
itemNameLabel = new JLabel("Item Name: ");
totalCostLabel = new JLabel("Total Cost: ");
calculateButton = new JButton("Calculate");
printButton = new JButton("Print");
// Add components to frame
add(itemIdLabel);
add(itemIdField);
add(quantityLabel);
add(quantityField);
add(itemNameLabel);
add(totalCostLabel);
add(calculateButton);
add(printButton);
// Add button listeners
calculateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
calculateTotalCost();
}
});
printButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
printFinalCost();
}
});
}
private void calculateTotalCost() {
String itemId = itemIdField.getText();
int quantity = Integer.parseInt(quantityField.getText());
if (itemNames.containsKey(itemId) && itemPrices.containsKey(itemId)) {
String itemName = itemNames.get(itemId);
double price = itemPrices.get(itemId);
double totalCost = price * quantity;
itemNameLabel.setText("Item Name: " + itemName);
totalCostLabel.setText("Total Cost: $" + totalCost);
} else {
itemNameLabel.setText("Item Name: ");
totalCostLabel.setText("Total Cost: ");
JOptionPane.showMessageDialog(this, "Invalid Item ID", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
private void printFinalCost() {
String[] discountOptions = {"None", "10%", "20%", "30%"};
String selectedDiscount = (String) JOptionPane.showInputDialog(this,
"Select Discount",
"Discount Options",
JOptionPane.QUESTION_MESSAGE,
null,
discountOptions,
discountOptions[0]);
double discount = 0;
if (selectedDiscount != null) {
switch (selectedDiscount) {
case "10%":
discount = 0.10;
break;
case "20%":
discount = 0.20;
break;
case "30%":
discount = 0.30;
break;
}
}
String itemName = itemNameLabel.getText().replace("Item Name: ", "");
String totalCostStr = totalCostLabel.getText().replace("Total Cost: $", "");
double totalCost = Double.parseDouble(totalCostStr);
double finalCost = totalCost * (1 - discount);
JOptionPane.showMessageDialog(this,
"Item Name: " + itemName + "\nTotal Cost: $" + totalCost + "\nDiscount: " +
selectedDiscount + "\nFinal Cost: $" + finalCost,
"Final Cost",
JOptionPane.INFORMATION_MESSAGE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ShoppingApp().setVisible(true);
}
});
}
}

Prog 1
package prog1;
import java.util.Scanner;
public class CountMatches {

public static int frequency( String source, String part ) {


if ( source == null || source.isEmpty() || part == null || part.isEmpty() )
return 0;
int count = 0;
for ( int pos = 0; (pos = source.indexOf( part, pos )) != -1; count++ )
pos += part.length();
return count;
}
public static void main( String[] args ) {
Scanner sc = new Scanner(System.in);
System.out.println("enter the string" ); // 2
String str = sc.nextLine();
System.out.println("enter the substring" ); // 1
String substr = sc.nextLine();
System.out.println( frequency( str, substr ) ); // 0
}
}
package prog1;
import java.util.Arrays;
import java.util.Scanner;
public class anagram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first string: ");
String a1 = scanner.nextLine();
System.out.print("Enter the second string: ");
String a2 = scanner.nextLine();
char[] a1chars = a1.toLowerCase().toCharArray();
char[] a2chars = a2.toLowerCase().toCharArray();
Arrays.sort(a1chars);
Arrays.sort(a2chars);
boolean isAnagram = Arrays.equals(a1chars, a2chars);
if(isAnagram == true) {
System.out.println("They are anagrams");
}
else
System.out.println("They are not anagrams");

scanner.close();
}
}

Prog 2
package prog2;
import java.util.ArrayList;
import java.util.List;
// Generic Stack class with a maximum size
class Stack<T> {
List<T> elements = new ArrayList<>();
final int maxSize;
// Constructor to set the maximum size
Stack(int maxSize) {
this.maxSize = maxSize;
}
// Push an element onto the stack
void push(T element) {
if (elements.size() < maxSize) {
elements.add(element);
}
}
// Pop an element from the stack
T pop() {
if (isEmpty()) {
return null; // Return null if stack is empty
}
return elements.remove(elements.size() - 1);
}
// Peek at the top element of the stack without removing it
T peek() {
if (isEmpty()) {
return null; // Return null if stack is empty
}
return elements.get(elements.size() - 1);
}
// Clear the stack
void clear() {
elements.clear();
}
// Check if the stack is empty
boolean isEmpty() {
return elements.isEmpty();
}
// Check if the stack is full
boolean isFull() {
return elements.size() >= maxSize;
}
// Display the elements of the stack
void display() {
if (isEmpty()) {
System.out.println("Stack is empty");
} else {
System.out.println("Stack contents: " + elements);
}
}
}
// Demonstration of Stack class with String and Integer
public class StackDemo {
public static void main(String[] args) {
// Stack of Strings with a maximum size of 2
Stack<String> stringStack = new Stack<>(2);
stringStack.push("Hello");
stringStack.push("World");
stringStack.display(); // Output: Stack contents: [Hello, World]
// Attempt to push another element (won't be added since stack is full)
stringStack.push("Overflow");
System.out.println("Peeked element: " + stringStack.peek()); // Output: Peeked element:
World
System.out.println("Popped element: " + stringStack.pop()); // Output: Popped element:
World
stringStack.display(); // Output: Stack contents: [Hello]
// Stack of Integers with a maximum size of 3
Stack<Integer> integerStack = new Stack<>(3);
integerStack.push(1);
integerStack.push(2);
integerStack.push(3);
integerStack.display(); // Output: Stack contents: [1, 2, 3]
// Attempt to push another element (won't be added since stack is full)
integerStack.push(4);
System.out.println("Peeked element: " + integerStack.peek()); // Output: Peeked element: 3
System.out.println("Popped element: " + integerStack.pop()); // Output: Popped element: 3
integerStack.display(); // Output: Stack contents: [1, 2]
integerStack.clear();
integerStack.display(); // Output: Stack is empty
}
}

Prog 3
PhoneSystem.java
package prog3;
import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class PhoneSystem {
private List<Call> missedCalls = new LinkedList<>();
// Add a missed call
public void addCall(String phoneNumber, String callerName, LocalDateTime callTime) {
missedCalls.add(new Call(phoneNumber, callerName, callTime));
}
// Display all missed calls
public void displayCalls() {
if (missedCalls.isEmpty()) {
System.out.println("No missed calls.");
} else {
System.out.println("Missed Calls:");
for (int i = 0; i < missedCalls.size(); i++) {
System.out.println((i + 1) + ". " + missedCalls.get(i));
}
}
}
// Handle user input
public void handleUserInput() {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Select an option:");
System.out.println("1. Add a missed call");
System.out.println("2. Delete a call");
System.out.println("3. Display all call details");
System.out.println("4. Exit");
int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline
if (choice == 4) break;
switch (choice) {
case 1:
System.out.println("Enter phone number:");
String phoneNumber = scanner.nextLine();
System.out.println("Enter caller name (or leave blank for private caller):");
String callerName = scanner.nextLine();
LocalDateTime callTime = LocalDateTime.now(); // Assuming current time
addCall(phoneNumber, callerName.isEmpty() ? null : callerName, callTime);
System.out.println("Missed call added.");
break;
case 2:
System.out.println("Enter the phone number to delete:");
String phoneNumberToDelete = scanner.nextLine();
deleteCall(phoneNumberToDelete);
break;
case 3:
displayCalls();
break;
default:
System.out.println("Invalid option.");
}
}
}
// Delete a specific call
private void deleteCall(String phoneNumber) {
boolean removed = missedCalls.removeIf(call ->
call.getPhoneNumber().equals(phoneNumber));
if (removed) {
System.out.println("Call deleted.");
} else {
System.out.println("Call not found.");
}
}
public static void main(String[] args) {
PhoneSystem phoneSystem = new PhoneSystem();
phoneSystem.addCall("123-456-7890", "Alice", LocalDateTime.now().minusHours(1));
phoneSystem.addCall("098-765-4321", null, LocalDateTime.now().minusHours(2));
phoneSystem.addCall("555-555-5555", "Bob", LocalDateTime.now().minusHours(3));
phoneSystem.handleUserInput();
}
}

Call.java
package prog3;
import java.time.LocalDateTime;
public class Call {
private String phoneNumber;
private String callerName;
private LocalDateTime callTime;
public Call(String phoneNumber, String callerName, LocalDateTime callTime) {
this.phoneNumber = phoneNumber;
this.callerName = callerName != null ? callerName : "private caller";
this.callTime = callTime;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getCallerName() {
return callerName;
}
public LocalDateTime getCallTime() {
return callTime;
}
@Override
public String toString() {
return "Number: " + phoneNumber + ", Name: " + callerName + ", Time: " + callTime;
}
}
Prog 4
Book.java
package prog4;
public class Book {
private int id;
private String title;
private String author;
private String publisher;
private double price;
public Book(int id, String title, String author, String publisher, double price) {
this.id = id;
this.title = title;
this.author = author;
this.publisher = publisher;
this.price = price;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getPublisher() {
return publisher;
}
public double getPrice() {
return price;
}
@Override
public String toString() {
return "ID: " + id + ", Title: " + title + ", Author: " + author +
", Publisher: " + publisher + ", Price: $" + price;
}
}
BookDatabase.java
package prog4;
import java.util.*;
import java.util.stream.Collectors;
public class BookDatabase {
private List<Book> books = new ArrayList<>();
private int nextId = 1;
// Add a book to the database
public void addBook(String title, String author, String publisher, double price) {
books.add(new Book(nextId++, title, author, publisher, price));
}
// Sort books by price and return a new list
public List<Book> getBooksSortedByPrice() {
return books.stream()
.sorted(Comparator.comparingDouble(Book::getPrice))
.collect(Collectors.toList());
}
// List all books by a specific author
public void listBooksByAuthor(String authorName) {
List<Book> booksByAuthor = books.stream()
.filter(book -> book.getAuthor().equalsIgnoreCase(authorName))
.collect(Collectors.toList());
if (booksByAuthor.isEmpty()) {
System.out.println("No books found for author: " + authorName);
} else {
booksByAuthor.forEach(System.out::println);
}
}
// Display all books
public void displayAllBooks() {
if (books.isEmpty()) {
System.out.println("No books in the database.");
} else {
books.forEach(System.out::println);
}
}
public static void main(String[] args) {
BookDatabase db = new BookDatabase();
db.addBook("Book A", "Author X", "Publisher Y", 29.99);
db.addBook("Book B", "Author X", "Publisher Z", 19.99);
db.addBook("Book C", "Author Z", "Publisher Y", 39.99);
System.out.println("Books sorted by price:");
List<Book> sortedBooks = db.getBooksSortedByPrice();
sortedBooks.forEach(System.out::println);
Scanner scanner = new Scanner(System.in);
System.out.println("Enter author name to search:");
String authorName = scanner.nextLine();
System.out.println("Books by " + authorName + ":");
db.listBooksByAuthor(authorName);
}
}

Prog 5
Book.java
package prog4;
public class Book {
private int id;
private String title;
private String author;
private String publisher;
private double price;
public Book(int id, String title, String author, String publisher, double price) {
this.id = id;
this.title = title;
this.author = author;
this.publisher = publisher;
this.price = price;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getPublisher() {
return publisher;
}
public double getPrice() {
return price;
}
@Override
public String toString() {
return "ID: " + id + ", Title: " + title + ", Author: " + author +
", Publisher: " + publisher + ", Price: $" + price;
}
}
BookDatabase.java
package prog5;
import java.util.*;
import java.util.stream.Collectors;
public class BookDatabase {
private List<Book> books = new ArrayList<>();
private int nextId = 1;
// Add a book to the database
public void addBook(String title, String author, String publisher, double price) {
books.add(new Book(nextId++, title, author, publisher, price));
}
// Get books with price greater than specified
public List<Book> getBooksAbovePrice(double price) {
return books.stream()
.filter(book -> book.getPrice() > price)
.collect(Collectors.toList());
}
// List all books by a specific publisher
public void listBooksByPublisher(String publisherName) {
List<Book> booksByPublisher = books.stream()
.filter(book -> book.getPublisher().equalsIgnoreCase(publisherName))
.collect(Collectors.toList());
if (booksByPublisher.isEmpty()) {
System.out.println("No books found for publisher: " + publisherName);
} else {
booksByPublisher.forEach(System.out::println);
}
}
// Display all books
public void displayAllBooks() {
if (books.isEmpty()) {
System.out.println("No books in the database.");
} else {
books.forEach(System.out::println);
}
}
public static void main(String[] args) {
BookDatabase db = new BookDatabase();
db.addBook("Book A", "Author X", "Publisher Y", 29.99);
db.addBook("Book B", "Author X", "Publisher Z", 19.99);
db.addBook("Book C", "Author Z", "Publisher Y", 39.99);
Scanner scanner = new Scanner(System.in);
System.out.println("Enter price to filter books:");
double price = scanner.nextDouble();
scanner.nextLine(); // Consume newline
System.out.println("Books with price greater than $" + price + ":");
List<Book> expensiveBooks = db.getBooksAbovePrice(price);
expensiveBooks.forEach(System.out::println);
System.out.println("Enter publisher name to search:");
String publisherName = scanner.nextLine();
System.out.println("Books by " + publisherName + ":");
db.listBooksByPublisher(publisherName);
}
}

Prog 8
package prog2;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
public class MainApp extends JFrame {
// JDBC URL, username, password
private static final String URL = "jdbc:mysql://localhost:3306/CustomerDB";
private static final String USER = "root";
private static final String PASSWORD = "";
// GUI components
private JTextField custNameField, stateField, creditLimitField;
private JButton insertButton, displayButton;
public MainApp() {
setTitle("Customer Database");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 2));
// Create and add GUI components
add(new JLabel("Customer Name:"));
custNameField = new JTextField();
add(custNameField);
add(new JLabel("State:"));
stateField = new JTextField();
add(stateField);
add(new JLabel("Credit Limit:"));
creditLimitField = new JTextField();
add(creditLimitField);
insertButton = new JButton("Insert");
insertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
insertCustomer();
}
});
add(insertButton);
displayButton = new JButton("Display");
displayButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
displayCustomers();
}
});
add(displayButton);
}
private void insertCustomer() {
String custName = custNameField.getText();
String state = stateField.getText();
String creditLimitStr = creditLimitField.getText();
double creditLimit = Double.parseDouble(creditLimitStr);
try (Connection connection = DriverManager.getConnection(URL, USER,
PASSWORD)) {
String query = "INSERT INTO Customer (CustName, State, Credit_Limit)
VALUES (?, ?, ?)";
PreparedStatement preparedStatement =
connection.prepareStatement(query);
preparedStatement.setString(1, custName);
preparedStatement.setString(2, state);
preparedStatement.setDouble(3, creditLimit);
preparedStatement.executeUpdate();
JOptionPane.showMessageDialog(this, "Customer inserted
successfully");
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "Error inserting customer",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
private void displayCustomers() {
try (Connection connection = DriverManager.getConnection(URL, USER,
PASSWORD)) {
String query = "SELECT * FROM Customer";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
StringBuilder results = new StringBuilder();
while (resultSet.next()) {
int custNo = resultSet.getInt("CustNo");
String custName = resultSet.getString("CustName");
String state = resultSet.getString("State");
double creditLimit = resultSet.getDouble("Credit_Limit");
results.append("CustNo: ").append(custNo)
.append(", CustName: ").append(custName)
.append(", State: ").append(state)
.append(", Credit Limit: ").append(creditLimit).append("\n");
}
JOptionPane.showMessageDialog(this, results.toString(), "Customer
List", JOptionPane.INFORMATION_MESSAGE);
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "Error displaying customers",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MainApp().setVisible(true);
}
});
}
}

Prog 9
package prog9;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class RepresentativeApp extends JFrame {
private JTextField repNoField, repNameField, stateField, commissionField,
rateField;
private JButton insertButton, displayButton;
private JTextArea displayArea;

// Database connection details


private static final String URL = "jdbc:mysql://localhost:3306/CustomerDB"; //
Update with your DB name
private static final String USER = "root"; // Update with your DB username
private static final String PASSWORD = ""; // Update with your DB password
public RepresentativeApp() {
setTitle("Representative Management");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(11, 2));
// Create components
JLabel repNoLabel = new JLabel("Rep No:");
repNoField = new JTextField();
JLabel repNameLabel = new JLabel("Rep Name:");
repNameField = new JTextField();
JLabel stateLabel = new JLabel("State:");
stateField = new JTextField();
JLabel commissionLabel = new JLabel("Commission:");
commissionField = new JTextField();
JLabel rateLabel = new JLabel("Rate:");
rateField = new JTextField();
insertButton = new JButton("Insert");
displayButton = new JButton("Display");
displayArea = new JTextArea();
displayArea.setEditable(false);
// Add components to frame
add(repNoLabel);
add(repNoField);
add(repNameLabel);
add(repNameField);
add(stateLabel);
add(stateField);
add(commissionLabel);
add(commissionField);
add(rateLabel);
add(rateField);
add(insertButton);
add(displayButton);
add(new JScrollPane(displayArea));
// Button listeners
insertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
insertRepresentative();
}
});
displayButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
displayRepresentatives();
}
});
}
private void insertRepresentative() {
String repNo = repNoField.getText();
String repName = repNameField.getText();
String state = stateField.getText();
String commission = commissionField.getText();
String rate = rateField.getText();
try (Connection conn = DriverManager.getConnection(URL, USER,
PASSWORD)) {
String sql = "INSERT INTO Representative (RepNo, RepName, State,
Commission, Rate) VALUES (?, ?, ?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, Integer.parseInt(repNo));
pstmt.setString(2, repName);
pstmt.setString(3, state);
pstmt.setBigDecimal(4, new java.math.BigDecimal(commission));
pstmt.setBigDecimal(5, new java.math.BigDecimal(rate));
pstmt.executeUpdate();
JOptionPane.showMessageDialog(this, "Representative added
successfully!");
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, "Error: " + e.getMessage(),
"Error", JOptionPane.ERROR_MESSAGE);
}
}
private void displayRepresentatives() {
try (Connection conn = DriverManager.getConnection(URL, USER,
PASSWORD);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM Representative")) {
StringBuilder sb = new StringBuilder();
while (rs.next()) {
sb.append("Rep No: ").append(rs.getInt("RepNo")).append("\n")
.append("Rep Name:
").append(rs.getString("RepName")).append("\n")
.append("State: ").append(rs.getString("State")).append("\n")
.append("Commission:
").append(rs.getBigDecimal("Commission")).append("\n")
.append("Rate: ").append(rs.getBigDecimal("Rate")).append("\n")
.append("--------------------------\n");
}
displayArea.setText(sb.toString());
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, "Error: " + e.getMessage(),
"Error", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new RepresentativeApp().setVisible(true);
}
});
}
}

Prog 10

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy