0% found this document useful (0 votes)
5 views7 pages

Java Cat 2

The document contains Java programs with explanations for a Password Strength Checker, Username Validator, Food Ordering System using JDBC, and a Student Registration Form using Swing and MySQL. Each program includes code snippets and detailed explanations of their functionality, including input handling, validation, and database interactions. The document serves as a guide for implementing these applications in Java.

Uploaded by

kangirene9705
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)
5 views7 pages

Java Cat 2

The document contains Java programs with explanations for a Password Strength Checker, Username Validator, Food Ordering System using JDBC, and a Student Registration Form using Swing and MySQL. Each program includes code snippets and detailed explanations of their functionality, including input handling, validation, and database interactions. The document serves as a guide for implementing these applications in Java.

Uploaded by

kangirene9705
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/ 7

📄 Java Programs with Explanations

✅ 1. Password Strength Checker


📌 Java Code:
import java.util.Scanner;

class PasswordStrength {
String password;

void setPassword(String password) {


this.password = password;
}

void checkStrength() {
boolean hasUpper = false, hasLower = false, hasDigit = false,
hasSpecial = false;

if (password.length() >= 8) {
for (char ch : password.toCharArray()) {
if (Character.isUpperCase(ch)) hasUpper = true;
else if (Character.isLowerCase(ch)) hasLower = true;
else if (Character.isDigit(ch)) hasDigit = true;
else hasSpecial = true;
}

if (hasUpper && hasLower && hasDigit && hasSpecial) {


System.out.println("Password is Strong.");
} else {
System.out.println("Password is Weak. Missing criteria.");
}
} else {
System.out.println("Password must be at least 8 characters.");
}
}
}

public class PasswordChecker {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PasswordStrength obj = new PasswordStrength();

System.out.print("Enter Password: ");


String input = sc.nextLine();

obj.setPassword(input);
obj.checkStrength();

sc.close();
}
}
📘 Explanation:

 Scanner is used to read user input.


 PasswordStrength class contains methods to set and validate the password.
 setPassword() stores the input using this keyword.
 checkStrength() checks for four criteria using Character methods:
o At least one uppercase letter
o At least one lowercase letter
o At least one digit
o At least one special character
 Boolean flags track whether these conditions are met.
 Final message is printed based on whether all conditions are satisfied.
 main() handles object creation, input, and method calls.

✅ 2. Username Validator
📌 Java Code:
import java.util.Scanner;

class Username {
String name;

void setUsername(String name) {


this.name = name;
}

void validate() {
boolean isValid = true;

if (name.length() < 6) {
System.out.println("Username must be at least 6 characters
long.");
isValid = false;
} else if (!Character.isLetter(name.charAt(0))) {
System.out.println("Username must start with a letter.");
isValid = false;
} else {
for (int i = 0; i < name.length(); i++) {
char ch = name.charAt(i);
if (!Character.isLetterOrDigit(ch)) {
System.out.println("Username can only contain letters
and digits.");
isValid = false;
break;
}
}
}

if (isValid) {
System.out.println("Username is valid.");
}
}
}

public class UsernameValidator {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Username user = new Username();

System.out.print("Enter username: ");


String input = sc.nextLine();

user.setUsername(input);
user.validate();

sc.close();
}
}

📘 Explanation:

 The Username class holds and validates the username.


 setUsername() stores the value using this.
 validate() performs three checks:
1. Minimum length of 6
2. Starts with a letter
3. Contains only letters and digits
 Character class methods are used for checking characters.
 Loop and conditional statements validate each rule and print feedback.

✅ 3. Food Ordering System (with JDBC)


💡 Requirements:

 MySQL database named: fooddb


 Table inside fooddb:

CREATE TABLE orders (


id INT AUTO_INCREMENT PRIMARY KEY,
total_amount INT NOT NULL
);

 Add MySQL JDBC connector to your project.


 Update MySQL credentials in the code (user, password).

📌 Java Code:
import java.util.Scanner;
import java.sql.*;
class FoodOrderJDBC {
int total = 0;

void displayMenu() {
System.out.println("Menu:");
System.out.println("1. Pizza - $10");
System.out.println("2. Burger - $5");
System.out.println("3. Coke - $2");
}

void takeOrder(Scanner sc) {


System.out.print("Do you want Pizza? (yes/no): ");
if (sc.nextLine().equalsIgnoreCase("yes")) total += 10;

System.out.print("Do you want Burger? (yes/no): ");


if (sc.nextLine().equalsIgnoreCase("yes")) total += 5;

System.out.print("Do you want Coke? (yes/no): ");


if (sc.nextLine().equalsIgnoreCase("yes")) total += 2;
}

void saveToDatabase() {
try {
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/fooddb", "root",
"yourpassword"
);

String sql = "INSERT INTO orders (total_amount) VALUES (?)";


PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, total);
stmt.executeUpdate();

conn.close();
System.out.println("Order saved to database.");
} catch (Exception e) {
e.printStackTrace();
}
}

void showBill() {
System.out.println("Total bill: $" + total);
}
}

public class FoodOrder {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
FoodOrderJDBC order = new FoodOrderJDBC();

order.displayMenu();
order.takeOrder(sc);
order.showBill();
order.saveToDatabase();

sc.close();
}
}
📘 Explanation:

 displayMenu(): Prints food items and prices.


 takeOrder(): Takes user input using Scanner and adds price to total.
 saveToDatabase():
o Connects to fooddb using JDBC.
o Inserts total_amount into the orders table.
o Uses PreparedStatement to avoid SQL injection.
 showBill(): Displays total cost on the console.
 main(): Controls flow — calls all methods in sequence.

✅ 4. Student Registration Form (Swing +


MySQL)
💡 Requirements:

 MySQL database named: studentdb


 Table inside studentdb:

CREATE TABLE students (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
age INT,
email VARCHAR(100),
course VARCHAR(100)
);

 Add JDBC driver to your project.


 Replace yourpassword with your actual MySQL root password.

📌 Java Code:
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;

class Student {
String name, email, course;
int age;

void setDetails(String name, int age, String email, String course) {


this.name = name;
this.age = age;
this.email = email;
this.course = course;
}
void saveToDatabase() {
try {
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/studentdb", "root",
"yourpassword"
);

String sql = "INSERT INTO students (name, age, email, course)


VALUES (?, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, name);
stmt.setInt(2, age);
stmt.setString(3, email);
stmt.setString(4, course);
stmt.executeUpdate();

conn.close();
System.out.println("Student registered in database.");
} catch (Exception e) {
e.printStackTrace();
}
}

void printDetails() {
System.out.println("Name : " + name);
System.out.println("Age : " + age);
System.out.println("Email : " + email);
System.out.println("Course : " + course);
}
}

public class StudentForm {


public static void main(String[] args) {
JFrame frame = new JFrame("Student Registration");

JLabel nameLabel = new JLabel("Name:");


JLabel ageLabel = new JLabel("Age:");
JLabel emailLabel = new JLabel("Email:");
JLabel courseLabel = new JLabel("Course:");

JTextField nameField = new JTextField();


JTextField ageField = new JTextField();
JTextField emailField = new JTextField();
JTextField courseField = new JTextField();
JButton submitButton = new JButton("Submit");

nameLabel.setBounds(30, 30, 100, 25);


ageLabel.setBounds(30, 60, 100, 25);
emailLabel.setBounds(30, 90, 100, 25);
courseLabel.setBounds(30, 120, 100, 25);
nameField.setBounds(130, 30, 150, 25);
ageField.setBounds(130, 60, 150, 25);
emailField.setBounds(130, 90, 150, 25);
courseField.setBounds(130, 120, 150, 25);
submitButton.setBounds(110, 160, 100, 30);

frame.add(nameLabel); frame.add(ageLabel); frame.add(emailLabel);


frame.add(courseLabel);
frame.add(nameField); frame.add(ageField); frame.add(emailField);
frame.add(courseField);
frame.add(submitButton);

frame.setSize(350, 250);
frame.setLayout(null);
frame.setVisible(true);

Student student = new Student();

submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String name = nameField.getText();
int age = Integer.parseInt(ageField.getText());
String email = emailField.getText();
String course = courseField.getText();

student.setDetails(name, age, email, course);


student.printDetails();
student.saveToDatabase();

JOptionPane.showMessageDialog(frame, "Submitted
Successfully!");
} catch (Exception ex) {
JOptionPane.showMessageDialog(frame, "Error: " +
ex.getMessage());
}
}
});
}
}

📘 Explanation:

 GUI Setup:
o JTextField and JButton capture input.
o Layout is absolute (setBounds()).
 Student class:
o setDetails() stores form data.
o printDetails() prints to console.
o saveToDatabase() connects to studentdb and inserts the form data.
 submitButton.addActionListener():
o Triggered when "Submit" is clicked.
o Retrieves form values, sets data, saves to DB, and shows a popup.

You might also like