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

Java File

The document contains Java code examples for creating various applications including an online exam program, a chess game, a chat application, a student management system, and an online billing system. Each example includes class structures and methods necessary for functionality such as user registration, question handling, game moves, and invoice generation. The code snippets demonstrate fundamental programming concepts and object-oriented design in Java.

Uploaded by

itsayaanrajhere
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)
5 views17 pages

Java File

The document contains Java code examples for creating various applications including an online exam program, a chess game, a chat application, a student management system, and an online billing system. Each example includes class structures and methods necessary for functionality such as user registration, question handling, game moves, and invoice generation. The code snippets demonstrate fundamental programming concepts and object-oriented design in Java.

Uploaded by

itsayaanrajhere
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

1. Create online exam program in java?

Ans:-
import [Link];
import [Link];
import [Link];
import [Link];

class Question {
private String questionText;
private String correctAnswer;

public Question(String questionText, String correctAnswer) {


[Link] = questionText;
[Link] = correctAnswer;
}

public String getQuestionText() {


return questionText;
}

public boolean isCorrect(String answer) {


return [Link](answer);
}
}

class Exam {
private ArrayList<Question> questions;
private int totalQuestions;

public Exam() {
[Link] = new ArrayList<>();
[Link] = 0;
}

public void addQuestion(String questionText, String


correctAnswer) {
Question question = new Question(questionText,
correctAnswer);
[Link](question);
totalQuestions++;
}

public int getTotalQuestions() {


return totalQuestions;
}

public Question getQuestion(int index) {


return [Link](index);
}
}

class User {
private String username;
private int score;

public User(String username) {


[Link] = username;
[Link] = 0;
}

public String getUsername() {


return username;
}

public int getScore() {


return score;
}

public void increaseScore() {


score++;
}
}

public class OnlineExamProgram {


private static Map<String, String> userCredentials = new
HashMap<>();
private static Map<String, User> loggedInUsers = new
HashMap<>();
private static Exam exam;

public static void main(String[] args) {


// Initialize the exam
initializeExam();

// Simulate user registration


registerUser("john", "password123");

// Simulate user login


User currentUser = loginUser("john", "password123");

if (currentUser != null) {
// Start the exam
startExam(currentUser);
}
}

private static void initializeExam() {


exam = new Exam();
[Link]("What is the capital of France?",
"Paris");
[Link]("What is the largest planet in our
solar system?", "Jupiter");
// Add more questions as needed
}

private static void registerUser(String username, String


password) {
[Link](username, password);
[Link]("User registered successfully.");
}

private static User loginUser(String username, String


password) {
if ([Link](username) &&
[Link](username).equals(password)) {
User user = new User(username);
[Link](username, user);
[Link]("Login successful.");
return user;
} else {
[Link]("Invalid credentials. Login failed.");
return null;
}
}

private static void startExam(User user) {


Scanner scanner = new Scanner([Link]);

[Link]("Welcome, " + [Link]() +


"! You are about to start the exam.");
for (int i = 0; i < [Link](); i++) {
Question currentQuestion = [Link](i);

[Link]("Question " + (i + 1) + ": " +


[Link]());
[Link]("Your answer: ");
String userAnswer = [Link]();

if ([Link](userAnswer)) {
[Link]("Correct!");
[Link]();
} else {
[Link]("Incorrect. The correct answer is:
" + [Link]());
}
}

[Link]("Exam completed. Your score: " +


[Link]() + "/" + [Link]());

// You can save the user's score to a database or perform


other actions here.

[Link]();
}
}
2. Create a chess game in java?
Ans:-
import [Link];

public class ChessGame {


public static void main(String[] args) {
Board board = new Board();
[Link]();
[Link]();

Scanner scanner = new Scanner([Link]);

while (![Link]()) {
[Link]("Enter your move (e.g., a2a4): ");
String move = [Link]();

if ([Link](move)) {
[Link](move);
[Link]();
} else {
[Link]("Invalid move! Try again.");
}
}

[Link]("Game Over. " +


[Link]());
[Link]();
}
}

class Board {
private char[][] board;
private boolean isWhiteTurn;
private boolean gameOver;

public void initialize() {


board = new char[8][8];
isWhiteTurn = true;
gameOver = false;

// Initialize the board with pieces


// ... (implementation depends on your representation)

// For simplicity, let's place a few pieces for testing


board[1][0] = 'P';
board[6][1] = 'p';
board[6][2] = 'p';
}

public void printBoard() {


// ... (implementation depends on your representation)
// Print the current state of the chess board
}

public boolean isValidMove(String move) {


// Check if the entered move is valid
// ... (implementation depends on your move validation
logic)
return true; // For simplicity, assuming all moves are valid
in this example
}

public void makeMove(String move) {


// Apply the move to the board
// ... (implementation depends on your move logic)
}

public boolean isGameOver() {


// Determine if the game is over
// ... (implementation depends on your game over
conditions)
return gameOver;
}

public String getGameResult() {


// Determine and return the result of the game
// ... (implementation depends on your game result
conditions)
return "Result"; // Placeholder result
}
}
3. Create a chat application in java?
Ans:- import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class ChatServer {


private ServerSocket serverSocket;
private List<ClientHandler> clients = new ArrayList<>();

public static void main(String[] args) {


ChatServer chatServer = new ChatServer();
[Link](5555);
}

public void start(int port) {


try {
serverSocket = new ServerSocket(port);
[Link]("Server is listening on port " + port);

while (true) {
Socket clientSocket = [Link]();
[Link]("New client connected: " +
clientSocket);

ClientHandler clientHandler = new


ClientHandler(clientSocket, this);
[Link](clientHandler);
new Thread(clientHandler).start();
}
} catch (IOException e) {
[Link]();
}
}

public void broadcastMessage(String message,


ClientHandler sender) {
for (ClientHandler client : clients) {
if (client != sender) {
[Link](message);
}
}
}

public void removeClient(ClientHandler clientHandler) {


[Link](clientHandler);
}
}
4. Create a student management system in java?
Ans:-
import [Link].*;
import [Link].*;
import [Link];
import [Link];
import [Link].*;

public class StudentManagementSystem extends JFrame {


private JTextField idField, nameField, ageField;
private JButton addButton, viewButton;

public StudentManagementSystem() {
setTitle("Student Management System");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

idField = new JTextField(10);


nameField = new JTextField(20);
ageField = new JTextField(5);

addButton = new JButton("Add Student");


viewButton = new JButton("View Students");

[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addStudent();
}
});

[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
viewStudents();
}
});
setLayout(new GridLayout(4, 2));

add(new JLabel("Student ID: "));


add(idField);
add(new JLabel("Student Name: "));
add(nameField);
add(new JLabel("Student Age: "));
add(ageField);
add(addButton);
add(viewButton);
}

private void addStudent() {


int id = [Link]([Link]());
String name = [Link]();
int age = [Link]([Link]());

try (Connection connection =


[Link]("jdbc:sqlite:[Link]");
Statement statement = [Link]())
{

[Link]("CREATE TABLE IF NOT


EXISTS students (id INT, name TEXT, age INT)");
PreparedStatement preparedStatement =
[Link]("INSERT INTO students VALUES
(?, ?, ?)");
[Link](1, id);
[Link](2, name);
[Link](3, age);
[Link]();
[Link](this, "Student added
successfully!");

} catch (SQLException ex) {


[Link]();
[Link](this, "Error adding
student!");
}
}

private void viewStudents() {


try (Connection connection =
[Link]("jdbc:sqlite:[Link]");
Statement statement = [Link]();
ResultSet resultSet = [Link]("SELECT
* FROM students")) {

StringBuilder result = new StringBuilder("Student List:\


n");
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
int age = [Link]("age");
[Link]("ID: ").append(id).append(", Name:
").append(name).append(", Age: ").append(age).append("\
n");
}

[Link](this,
[Link]());

} catch (SQLException ex) {


[Link]();
[Link](this, "Error viewing
students!");
}
}

public static void main(String[] args) {


[Link](new Runnable() {
@Override
public void run() {
new StudentManagementSystem().setVisible(true);
}
});
}
}
5. Create an online billing system in java?
Ans:- import [Link];
import [Link];
import [Link];

class Customer {
String name;
double balance;

public Customer(String name, double balance) {


[Link] = name;
[Link] = balance;
}
}

class Invoice {
int invoiceNumber;
String customerName;
double amount;

public Invoice(int invoiceNumber, String customerName,


double amount) {
[Link] = invoiceNumber;
[Link] = customerName;
[Link] = amount;
}
}

public class OnlineBillingSystem {


private static List<Customer> customers = new
ArrayList<>();
private static List<Invoice> invoices = new ArrayList<>();
private static int invoiceCounter = 1;

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

while (true) {
[Link]("1. Add Customer");
[Link]("2. Generate Invoice");
[Link]("3. Display Invoices");
[Link]("4. Exit");
[Link]("Enter your choice: ");
int choice = [Link]();

switch (choice) {
case 1:
addCustomer();
break;
case 2:
generateInvoice();
break;
case 3:
displayInvoices();
break;
case 4:
[Link]("Exiting the billing system.
Goodbye!");
[Link](0);
default:
[Link]("Invalid choice. Please try
again.");
}
}
}

private static void addCustomer() {


Scanner scanner = new Scanner([Link]);
[Link]("Enter customer name: ");
String name = [Link]();
[Link]("Enter initial balance: ");
double balance = [Link]();

Customer customer = new Customer(name, balance);


[Link](customer);

[Link]("Customer added successfully!");


}

private static void generateInvoice() {


Scanner scanner = new Scanner([Link]);
[Link]("Enter customer name: ");
String customerName = [Link]();
Customer customer = findCustomer(customerName);

if (customer == null) {
[Link]("Customer not found.");
return;
}

[Link]("Enter invoice amount: ");


double amount = [Link]();

Invoice invoice = new Invoice(invoiceCounter++,


customerName, amount);
[Link](invoice);

[Link] -= amount;

[Link]("Invoice generated successfully!");


}

private static void displayInvoices() {


[Link]("Invoices:");
for (Invoice invoice : invoices) {
[Link]("Invoice Number: " +
[Link]);
[Link]("Customer Name: " +
[Link]);
[Link]("Amount: " + [Link]);
[Link]("-----------");
}
}

private static Customer findCustomer(String name) {


for (Customer customer : customers) {
if ([Link](name)) {
return customer;
}
}
return null;
}
}

You might also like