[go: up one dir, main page]

0% found this document useful (0 votes)
3 views30 pages

Java code

The document contains multiple Java classes demonstrating various applications such as a banking system, student profile management, a Tic Tac Toe game, university course management, personal finance tracking, a to-do list application, and a student schedule organizer. Each class includes methods for specific functionalities like account creation, GPA calculation, game mechanics, task management, and tracking academic activities. The main method in each class serves as the entry point to execute the respective application.

Uploaded by

mecubra10
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)
3 views30 pages

Java code

The document contains multiple Java classes demonstrating various applications such as a banking system, student profile management, a Tic Tac Toe game, university course management, personal finance tracking, a to-do list application, and a student schedule organizer. Each class includes methods for specific functionalities like account creation, GPA calculation, game mechanics, task management, and tracking academic activities. The main method in each class serves as the entry point to execute the respective application.

Uploaded by

mecubra10
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/ 30

1

import java.util.HashMap;
import java.util.Scanner;

class Account {
private String accountNumber;
private String accountHolderName;
private double balance;

public Account(String accountNumber, String accountHolderName) {


this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.balance = 0.0;
}

public String getAccountNumber() {


return accountNumber;
}

public String getAccountHolderName() {


return accountHolderName;
}

public double getBalance() {


return balance;
}

public void deposit(double amount) {


if (amount > 0) {
balance += amount;
System.out.println("Deposited: $" + amount);
} else {
System.out.println("Deposit amount must be positive.");
}
}

public void withdraw(double amount) {


if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrew: $" + amount);
} else if (amount > balance) {
System.out.println("Insufficient funds.");
} else {
System.out.println("Withdrawal amount must be positive.");
}
}
}

public class JohnDoeBank {


private HashMap<String, Account> accounts;
private Scanner scanner;

public JohnDoeBank() {
accounts = new HashMap<>();
scanner = new Scanner(System.in);
}

public void createAccount() {


System.out.print("Enter account number: ");
String accountNumber = scanner.nextLine();
System.out.print("Enter account holder name: ");
String accountHolderName = scanner.nextLine();

if (accounts.containsKey(accountNumber)) {
System.out.println("Account with this number already exists.");
} else {
Account newAccount = new Account(accountNumber, accountHolderName);
accounts.put(accountNumber, newAccount);
System.out.println("Account created successfully for " + accountHolderName);
}
}

public void deposit() {


System.out.print("Enter account number: ");
String accountNumber = scanner.nextLine();
Account account = accounts.get(accountNumber);

if (account != null) {
System.out.print("Enter amount to deposit: ");
double amount = scanner.nextDouble();
scanner.nextLine(); // Consume newline
account.deposit(amount);
} else {
System.out.println("Account not found.");
}
}

public void withdraw() {


System.out.print("Enter account number: ");
String accountNumber = scanner.nextLine();
Account account = accounts.get(accountNumber);

if (account != null) {
System.out.print("Enter amount to withdraw: ");
double amount = scanner.nextDouble();
scanner.nextLine(); // Consume newline
account.withdraw(amount);
} else {
System.out.println("Account not found.");
}
}

public void displayMenu() {


System.out.println("\nWelcome to John Doe Bank");
System.out.println("1. Create Account");
System.out.println("2. Deposit Money");
System.out.println("3. Withdraw Money");
System.out.println("4. Exit");
System.out.print("Choose an option: ");
}

public void start() {


while (true) {
displayMenu();
int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline

switch (choice) {
case 1:
createAccount();
break;
case 2:
deposit();
break;
case 3:
withdraw();
break;
case 4:
System.out.println("Thank you for using John Doe Bank. Goodbye!");
return;
default:
System.out.println("Invalid option. Please try again.");
}
}
}

public static void main(String[] args) {


JohnDoeBank bank = new JohnDoeBank();
bank.start();
}
}

2
public class StudentProfile {
private String name;
private String studentID;
private double gpa;

public StudentProfile(String name, String studentID, double gpa) {


this.name = name;
this.studentID = studentID;
this.gpa = gpa;
}

public String calculateAcademicStanding() {


if (gpa >= 3.5) {
return "Honor Roll";
} else if (gpa >= 2.0) {
return "Good Standing";
} else {
return "Academic Probation";
}
}

public String getName() {


return name;
}

public String getStudentID() {


return studentID;
}

public double getGpa() {


return gpa;
}

public static void main(String[] args) {

StudentProfile student = new StudentProfile("Kunle Moshood", "123456", 3.8);

System.out.println("Student Name: " + student.getName());


System.out.println("Student ID: " + student.getStudentID());
System.out.println("GPA: " + student.getGpa());
System.out.println("Academic Standing: " + student.calculateAcademicStanding());
}
}

3
import java.util.Random;
import java.util.Scanner;
public class TicTacToe {
private char[][] board;
private char currentPlayer;
private static final char PLAYER = 'X';
private static final char COMPUTER = 'O';
private static final int SIZE = 3;

public TicTacToe() {
board = new char[SIZE][SIZE];
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
board[i][j] = ' ';
}
}
currentPlayer = PLAYER;
}

public void printBoard() {


System.out.println("Current Board:");
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
System.out.print(board[i][j]);
if (j < SIZE - 1) System.out.print("|");
}
System.out.println();
if (i < SIZE - 1) System.out.println("-----");
}
}

public boolean isBoardFull() {


for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if (board[i][j] == ' ') {
return false;
}
}
}
return true;
}
public boolean checkWin(char player) {

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


if ((board[i][0] == player && board[i][1] == player && board[i][2] == player) ||
(board[0][i] == player && board[1][i] == player && board[2][i] == player)) {
return true;
}
}
M
if ((board[0][0] == player && board[1][1] == player && board[2][2] == player) ||
(board[0][2] == player && board[1][1] == player && board[2][0] == player)) {
return true;
}
return false;
}

public void playerMove() {


Scanner scanner = new Scanner(System.in);
int row, col;
while (true) {
System.out.print("Enter your move (row and column: 0, 1, or 2): ");
row = scanner.nextInt();
col = scanner.nextInt();
if (row >= 0 && row < SIZE && col >= 0 && col < SIZE && board[row][col] == ' ') {
board[row][col] = PLAYER;
break;
} else {
System.out.println("This move is not valid. Try again.");
}
}
}

public void computerMove() {


Random random = new Random();
int row, col;
while (true) {
row = random.nextInt(SIZE);
col = random.nextInt(SIZE);
if (board[row][col] == ' ') {
board[row][col] = COMPUTER;
break;
}
}
System.out.println("Computer placed 'O' in position: " + row + ", " + col);
}

public void playGame() {


while (true) {
printBoard();
if (currentPlayer == PLAYER) {
playerMove();
if (checkWin(PLAYER)) {
printBoard();
System.out.println("Congratulations, Ronaldo! You win!");
break;
}
currentPlayer = COMPUTER;
} else {
computerMove();
if (checkWin(COMPUTER)) {
printBoard();
System.out.println("Computer wins! Better luck next time, John Doe.");
break;
}
currentPlayer = PLAYER;
}
if (isBoardFull()) {
printBoard();
System.out.println("It's a draw!");
break;
}
}
}

public static void main(String[] args) {


TicTacToe game = new TicTacToe();
game.playGame();
}
}
4
import java.util.ArrayList;
import java.util.List;

public class UniversityCourse {


private String courseName;
private String courseCode;
private int credits;

public UniversityCourse(String courseName, String courseCode, int credits) {


this.courseName = courseName;
this.courseCode = courseCode;
this.credits = credits;
}

public String getCourseName() {


return courseName;
}

public String getCourseCode() {


return courseCode;
}

public int getCredits() {


return credits;
}

public String toString() {


return courseCode + ": " + courseName + " (" + credits + " credits)";
}

public static int calculateTotalCredits(List<UniversityCourse> completedCourses) {


int totalCredits = 0;
for (UniversityCourse course : completedCourses) {
totalCredits += course.getCredits();
}
return totalCredits;
}

public static void main(String[] args) {

UniversityCourse course1 = new UniversityCourse("Introduction to Computer Science",


"CS101", 3);
UniversityCourse course2 = new UniversityCourse("Data Structures", "CS201", 4);
UniversityCourse course3 = new UniversityCourse("Database Management Systems",
"CS301", 3);

List<UniversityCourse> completedCourses = new ArrayList<>();


completedCourses.add(course1);
completedCourses.add(course2);
completedCourses.add(course3);

int totalCredits = UniversityCourse.calculateTotalCredits(completedCourses);

System.out.println("Completed Courses:");
for (UniversityCourse course : completedCourses) {
System.out.println(course);
}
System.out.println("Total Credits Earned: " + totalCredits);
}
}

5
public class PersonalFinance {
private double income;
private double expenses;
private double savings;
public PersonalFinance(double income, double expenses, double savings) {
this.income = income;
this.expenses = expenses;
this.savings = savings;
}

public double getIncome() {


return income;
}

public double getExpenses() {


return expenses;
}

public double getSavings() {


return savings;
}

public double calculateNetWorth() {


return savings + (income - expenses);
}

public static void main(String[] args) {

double income = 3000.00; // Monthly income


double expenses = 2000.00; // Monthly expenses
double savings = 5000.00; // Current savings

PersonalFinance finance = new PersonalFinance(income, expenses, savings);

double netWorth = finance.calculateNetWorth();


System.out.println("Monthly Income: $" + finance.getIncome());
System.out.println("Monthly Expenses: $" + finance.getExpenses());
System.out.println("Current Savings: $" + finance.getSavings());
System.out.println("Net Worth: $" + netWorth);
}
}
6
import java.util.ArrayList;
import java.util.Scanner;

class Task {
private String description;
private boolean isCompleted;

public Task(String description) {


this.description = description;
this.isCompleted = false;
}

public String getDescription() {


return description;
}

public boolean isCompleted() {


return isCompleted;
}

public void markAsCompleted() {


isCompleted = true;
}

public String toString() {


return (isCompleted ? "[X] " : "[ ] ") + description;
}
}

public class ToDoListApp {


private ArrayList<Task> tasks;
private Scanner scanner;

public ToDoListApp() {
tasks = new ArrayList<>();
scanner = new Scanner(System.in);
}

public void addTask() {


System.out.print("Enter the task description: ");
String description = scanner.nextLine();
tasks.add(new Task(description));
System.out.println("Task added: " + description);
}

public void removeTask() {


System.out.print("Enter the task number to remove (1 to " + tasks.size() + "): ");
int taskNumber = scanner.nextInt();
scanner.nextLine(); // Consume newline

if (taskNumber > 0 && taskNumber <= tasks.size()) {


Task removedTask = tasks.remove(taskNumber - 1);
System.out.println("Removed task: " + removedTask.getDescription());
} else {
System.out.println("Invalid task number.");
}
}

public void markTaskAsCompleted() {


System.out.print("Enter the task number to mark as completed (1 to " + tasks.size() + "): ");
int taskNumber = scanner.nextInt();
scanner.nextLine(); // Consume newline

if (taskNumber > 0 && taskNumber <= tasks.size()) {


tasks.get(taskNumber - 1).markAsCompleted();
System.out.println("Marked task as completed: " + tasks.get(taskNumber -
1).getDescription());
} else {
System.out.println("Invalid task number.");
}
}

public void displayTasks() {


System.out.println("\nTo-Do List:");
for (int i = 0; i < tasks.size(); i++) {
System.out.println((i + 1) + ". " + tasks.get(i));
}
}

public void displayMenu() {


System.out.println("\nTo-Do List Menu:");
System.out.println("1. Add Task");
System.out.println("2. Remove Task");
System.out.println("3. Mark Task as Completed");
System.out.println("4. Display Tasks");
System.out.println("5. Exit");
System.out.print("Choose an option: ");
}

public void start() {


while (true) {
displayMenu();
int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline

switch (choice) {
case 1:
addTask();
break;
case 2:
removeTask();
break;
case 3:
markTaskAsCompleted();
break;
case 4:
displayTasks();
break;
case 5:
System.out.println("Thank you for using the To-Do List App. Goodbye, Ronaldo the
Goat!");
return;
default:
System.out.println("Invalid option. Please try again.");
}
}
}

public static void main(String[] args) {


ToDoListApp app = new ToDoListApp();
app.start();
}
}

7
import java.util.HashMap;
import java.util.Map;

public class StudentSchedule {


private Map<String, Integer> classes; // Day of the week mapped to the number of classes
private Map<String, Integer> assignments; // Day of the week mapped to the number of
assignments

public StudentSchedule() {
classes = new HashMap<>();
assignments = new HashMap<>();
}

public void addClasses(String day, int numberOfClasses) {


classes.put(day, classes.getOrDefault(day, 0) + numberOfClasses);
}

public void addAssignments(String day, int numberOfAssignments) {


assignments.put(day, assignments.getOrDefault(day, 0) + numberOfAssignments);
}

public String calculateBusiestDay() {


String busiestDay = "";
int maxActivities = 0;

for (String day : classes.keySet()) {


int totalActivities = classes.get(day) + assignments.getOrDefault(day, 0);
if (totalActivities > maxActivities) {
maxActivities = totalActivities;
busiestDay = day;
}
}

for (String day : assignments.keySet()) {


if (!classes.containsKey(day)) {
int totalActivities = assignments.get(day);
if (totalActivities > maxActivities) {
maxActivities = totalActivities;
busiestDay = day;
}
}
}

return busiestDay;
}

public static void main(String[] args) {

StudentSchedule schedule = new StudentSchedule();

schedule.addClasses("Monday", 3);
schedule.addClasses("Tuesday", 2);
schedule.addClasses("Wednesday", 4);
schedule.addClasses("Thursday", 1);
schedule.addClasses("Friday", 2);
schedule.addAssignments("Monday", 1);
schedule.addAssignments("Wednesday", 2);
schedule.addAssignments("Friday", 3);

String busiestDay = schedule.calculateBusiestDay();


System.out.println("The busiest day of the week is: " + busiestDay);
}
}
8
import java.util.HashMap;
import java.util.Map;

public class CareerGoals {


private String careerAspirations;
private Map<String, Integer> skills; // Skill name mapped to proficiency level (1-5)
private int yearsOfExperience;

public CareerGoals(String careerAspirations, int yearsOfExperience) {


this.careerAspirations = careerAspirations;
this.yearsOfExperience = yearsOfExperience;
this.skills = new HashMap<>();
}

public void addSkill(String skill, int proficiency) {


if (proficiency < 1 || proficiency > 5) {
System.out.println("Proficiency level must be between 1 and 5.");
} else {
skills.put(skill, proficiency);
}
}

public String calculateCareerReadiness() {


int totalProficiency = 0;
for (int proficiency : skills.values()) {
totalProficiency += proficiency;
}

int averageProficiency = skills.size() > 0 ? totalProficiency / skills.size() : 0;

if (yearsOfExperience >= 5 && averageProficiency >= 4) {


return "Highly Ready for Career Opportunities";
} else if (yearsOfExperience >= 3 && averageProficiency >= 3) {
return "Moderately Ready for Career Opportunities";
} else {
return "Needs Improvement for Career Readiness";
}
}

public static void main(String[] args) {

CareerGoals myCareerGoals = new CareerGoals("Software Engineer", 4);

myCareerGoals.addSkill("Java Programming", 4);


myCareerGoals.addSkill("Web Development", 3);
myCareerGoals.addSkill("Database Management", 5);
myCareerGoals.addSkill("Problem Solving", 4);

String readiness = myCareerGoals.calculateCareerReadiness();


System.out.println("Career Aspirations: " + myCareerGoals.careerAspirations);
System.out.println("Years of Experience: " + myCareerGoals.yearsOfExperience);
System.out.println("Career Readiness: " + readiness);
}
}

9
public class OddEvenThreads {

public static void main(String[] args) {

Thread oddThread = new Thread(new OddNumberPrinter());

Thread evenThread = new Thread(new EvenNumberPrinter());

oddThread.start();
evenThread.start();
}
}

class OddNumberPrinter implements Runnable {


@Override
public void run() {
for (int i = 1; i <= 20; i += 2) {
System.out.println("Odd: " + i);
try {
Thread.sleep(100); // Sleep for a short duration to simulate work
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}

class EvenNumberPrinter implements Runnable {


@Override
public void run() {
for (int i = 0; i <= 20; i += 2) {
System.out.println("Even: " + i);
try {
Thread.sleep(100); // Sleep for a short duration to simulate work
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}

10
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

public class WordCount {


public static void main(String[] args) {

String filePath = “C:\\Users\\USER\\Documents\\filename.txt”;


int wordCount = 0;

try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {


String line;
while ((line = br.readLine()) != null) {

StringTokenizer tokenizer = new StringTokenizer(line);


wordCount += tokenizer.countTokens();
}
} catch (IOException e) {
System.err.println("Error reading the file: " + e.getMessage());
}

System.out.println("Total number of words: " + wordCount);


}
}

You might also like