Java Projects

Learn by doing!

BUILD A  CALCULATOR 

Here's a simple console-based Calculator application implemented in Java.

This code allows the user to input two numbers and select an operation (+, -, *, /), and then it performs the calculation and displays the result.

import java.util.Scanner;

public class Calculator {
     public static void main(String[] args) {
         Scanner scanner = new Scanner(System.in);
         double num1, num2, result;
         char operator;
          System.out.println("Welcome to the Calculator App!");

          System.out.print("Enter first number: ");
         num1 = scanner.nextDouble();

          System.out.print("Enter second number: ");
         num2 = scanner.nextDouble();

          System.out.print("Enter operator (+, -, *, /): ");
         operator = scanner.next().charAt(0);

          switch (operator) {
             case '+':
                 result = num1 + num2;
                 System.out.println("Result: " + result);
                 break;
             case '-':
                 result = num1 - num2;
                 System.out.println("Result: " + result);
                 break;
             case '*':
                 result = num1 * num2;
                 System.out.println("Result: " + result);
                 break;
             case '/':
                 if (num2 != 0) {
                     result = num1 / num2;
                     System.out.println("Result: " + result);
                 } else {
                     System.out.println("Error: Cannot divide by zero!");
                 }
                 break;
             default:
                 System.out.println("Error: Invalid operator!");
         }
     }

BUILD A  Temperature converteR 

Here's a simple Temperature Converter application in Java that converts between Celsius and Fahrenheit.

This code prompts the user to enter a temperature and then asks for the type of conversion they want to perform (Celsius to Fahrenheit or Fahrenheit to Celsius). It then performs the conversion and displays the result.

import java.util.Scanner;

public class TemperatureConverter {
     public static void main(String[] args) {
         Scanner scanner = new Scanner(System.in);
         double temperature;
         char choice;

         System.out.println("Welcome to the Temperature Converter App!");

         System.out.print("Enter the temperature: ");
         temperature = scanner.nextDouble();

         System.out.println("Select the conversion type:");
         System.out.println("1. Celsius to Fahrenheit");
         System.out.println("2. Fahrenheit to Celsius");
         System.out.print("Enter your choice (1 or 2): ");
         choice = scanner.next().charAt(0);

          switch (choice) {
             case '1':
                 double fahrenheit = celsiusToFahrenheit(temperature);
                 System.out.println(temperature + " Celsius is equal to " + fahrenheit + " Fahrenheit");
                 break;
             case '2':
                 double celsius = fahrenheitToCelsius(temperature);
                 System.out.println(temperature + " Fahrenheit is equal to " + celsius + " Celsius");
                 break;
             default:
                 System.out.println("Invalid choice!");
         }
     }

     public static double celsiusToFahrenheit(double celsius) {
         return (celsius * 9 / 5) + 32;
     }

     public static double fahrenheitToCelsius(double fahrenheit) {
         return (fahrenheit - 32) * 5 / 9;
     }

BUILD A  To-Do List 

Here's a simple To-Do-List application implemented in Java.

This code allows users to add tasks, remove tasks, and list all tasks in the to-do list. The tasks are stored in an ArrayList. The user is presented with a menu to choose from different options. They can continue adding, removing, and listing tasks until they choose to quit the application.

import java.util.ArrayList;
import java.util.Scanner;

public class ToDoList {
     private static ArrayList tasks = new ArrayList<>();
     private static Scanner scanner = new Scanner(System.in);

     public static void main(String[] args) {
         boolean quit = false;

          while (!quit) {
             printMenu();
             int choice = scanner.nextInt();
             scanner.nextLine(); // Consume newline character

             switch (choice) {
                 case 1:
                     addTask();
                     break;
                 case 2:
                     removeTask();
                     break;
                 case 3:
                     listTasks();
                     break;
                 case 4:
                     quit = true;
                     System.out.println("Exiting the application...");
                     break;
                 default:
                     System.out.println("Invalid choice! Please enter a valid option.");
             }
         }
     }

     private static void printMenu() {
         System.out.println("n--- To-Do List Application ---");
         System.out.println("1. Add a Task");
         System.out.println("2. Remove a Task");
         System.out.println("3. List Tasks");
         System.out.println("4. Quit");
         System.out.print("Enter your choice: ");
     }

     private static void addTask() {
         System.out.print("Enter task description: ");
         String task = scanner.nextLine();
         tasks.add(task);
         System.out.println("Task added successfully!");
     }

     private static void removeTask() {
         if (tasks.isEmpty()) {
             System.out.println("No tasks to remove!");
             return;
         }
         System.out.print("Enter task number to remove: ");
         int taskNumber = scanner.nextInt();
         scanner.nextLine(); // Consume newline character
         if (taskNumber >= 1 && taskNumber <= tasks.size()) {
             String removedTask = tasks.remove(taskNumber - 1);
             System.out.println("Task '" + removedTask + "' removed successfully!");
         } else {
             System.out.println("Invalid task number!");
         }
     }

     private static void listTasks() {
         if (tasks.isEmpty()) {
             System.out.println("No tasks added yet!");
             return;
         }
         System.out.println("n--- Task List ---");
         for (int i = 0; i < tasks.size(); i++) {
             System.out.println((i + 1) + ". " + tasks.get(i));
         }
     }

BUILD AN  Address Book 

Here's a simple Address Book application implemented in Java.

This code allows users to add contacts, search for a contact by name, and list all contacts in the address book. The contacts are stored in a HashMap where the name of the contact is the key and the phone number is the value. The user is presented with a menu to choose from different options. They can continue adding, searching, and listing contacts until they choose to quit the application.

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

public class AddressBook {
     private static Map contacts = new HashMap<>();
     private static Scanner scanner = new Scanner(System.in);

     public static void main(String[] args) {
         boolean quit = false;

         while (!quit) {
             printMenu();
             int choice = scanner.nextInt();
             scanner.nextLine(); // Consume newline character

             switch (choice) {
                 case 1:
                     addContact();
                     break;
                 case 2:
                     searchContact();
                     break;
                 case 3:
                     listContacts();
                     break;
                 case 4:
                     quit = true;
                     System.out.println("Exiting the application...");
                     break;
                 default:
                     System.out.println("Invalid choice! Please enter a valid option.");
             }
         }
     }

     private static void printMenu() {
         System.out.println("n--- Address Book Application ---");
         System.out.println("1. Add a Contact");
         System.out.println("2. Search for a Contact");
         System.out.println("3. List Contacts");
         System.out.println("4. Quit");
         System.out.print("Enter your choice: ");
     }

     private static void addContact() {
         System.out.print("Enter contact name: ");
         String name = scanner.nextLine();
         System.out.print("Enter contact number: ");
         String number = scanner.nextLine();
         contacts.put(name, number);
         System.out.println("Contact added successfully!");
     }

     private static void searchContact() {
         System.out.print("Enter contact name to search: ");
         String name = scanner.nextLine();
         if (contacts.containsKey(name)) {
             String number = contacts.get(name);
             System.out.println("Contact found:");
             System.out.println("Name: " + name + ", Number: " + number);
         } else {
             System.out.println("Contact not found!");
         }
     }

     private static void listContacts() {
         if (contacts.isEmpty()) {
             System.out.println("No contacts added yet!");
             return;
         }
         System.out.println("n--- Contact List ---");
         for (Map.Entry entry : contacts.entrySet()) {
               System.out.println("Name: " + entry.getKey() + ", Number: " + entry.getValue());
         }
     }

BUILD AN  Expense Tracker 

Here's a simple Expense Tracker application implemented in Java.

This code allows users to add expenses and view a list of all expenses along with their total. The expenses are stored in a HashMap where the description of the expense is the key and the amount is the value. The user is presented with a menu to choose from different options. They can continue adding expenses, viewing expenses, and quit the application whenever they want.

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

public class ExpenseTracker {
     private static Map expenses = new HashMap<>();
     private static Scanner scanner = new Scanner(System.in);

     public static void main(String[] args) {
         boolean quit = false;

          while (!quit) {
             printMenu();
             int choice = scanner.nextInt();
             scanner.nextLine(); // Consume newline character

             switch (choice) {
                 case 1:
                     addExpense();
                     break;
                 case 2:
                     viewExpenses();
                     break;
                 case 3:
                     quit = true;
                     System.out.println("Exiting the application...");
                     break;
                 default:
                     System.out.println("Invalid choice! Please enter a valid option.");
             }
         }
     }

     private static void printMenu() {
         System.out.println("n--- Expense Tracker Application ---");
         System.out.println("1. Add an Expense");
         System.out.println("2. View Expenses");
         System.out.println("3. Quit");
         System.out.print("Enter your choice: ");
     }

     private static void addExpense() {
         System.out.print("Enter expense description: ");
         String description = scanner.nextLine();
         System.out.print("Enter expense amount: ");
         double amount = scanner.nextDouble();
         scanner.nextLine(); // Consume newline character
         expenses.put(description, amount);
         System.out.println("Expense added successfully!");
     }

     private static void viewExpenses() {
         if (expenses.isEmpty()) {
             System.out.println("No expenses added yet!");
             return;
         }
         System.out.println("n--- Expenses ---");
         double total = 0;
         for (Map.Entry entry : expenses.entrySet()) {
             String description = entry.getKey();
             double amount = entry.getValue();
             System.out.println("Description: " + description + ", Amount: $" + amount);
             total += amount;
         }
         System.out.println("Total Expenses: $" + total);
     }

BUILD A  Text-Based RPG 

Here's a simplified text-based RPG game implemented in Java.

In this game, the player faces an enemy with a fixed amount of health (100). The player also has a fixed amount of health (100). Each turn, the player can choose to attack the enemy or run away. If the player attacks, a random amount of damage within a certain range is dealt to the enemy, and the enemy retaliates with its own attack. The game continues until either the player or the enemy's health reaches zero. If the player's health reaches zero, the game ends in defeat. If the enemy's health reaches zero, the player wins.

import java.util.Random;
import java.util.Scanner;

public class TextBasedRPG {
     private static final int MAX_ENEMY_HEALTH = 100;
     private static final int PLAYER_HEALTH = 100;
     private static final int PLAYER_ATTACK_MIN = 10;
     private static final int PLAYER_ATTACK_MAX = 20;
     private static final int ENEMY_ATTACK_MIN = 5;
     private static final int ENEMY_ATTACK_MAX = 15;

     private static int playerHealth = PLAYER_HEALTH;
     private static int enemyHealth = MAX_ENEMY_HEALTH;
     private static Scanner scanner = new Scanner(System.in);
     private static Random random = new Random();

     public static void main(String[] args) {
         System.out.println("Welcome to the Text-Based RPG!");

         while (playerHealth > 0 && enemyHealth > 0) {
             System.out.println("nPlayer Health: " + playerHealth);
             System.out.println("Enemy Health: " + enemyHealth);
             System.out.println("1. Attack");
             System.out.println("2. Run");
             System.out.print("Choose your action: ");
             int choice = scanner.nextInt();

             switch (choice) {
                 case 1:
                     playerAttack();
                     if (enemyHealth <= 0) {
                         System.out.println("You defeated the enemy!");
                         break;
                     }
                     enemyAttack();
                     break;
                 case 2:
                     System.out.println("You ran away!");
                     return;
                 default:
                     System.out.println("Invalid choice! Please try again.");
             }
         }

         if (playerHealth <= 0) {
             System.out.println("Game Over! You were defeated.");
         } else {
             System.out.println("Congratulations! You won the game.");
         }
     }

     private static void playerAttack() {
         int damage = random.nextInt(PLAYER_ATTACK_MAX - PLAYER_ATTACK_MIN + 1) + PLAYER_ATTACK_MIN;
         enemyHealth -= damage;
         System.out.println("You hit the enemy for " + damage + " damage!");
     }

     private static void enemyAttack() {
         int damage = random.nextInt(ENEMY_ATTACK_MAX - ENEMY_ATTACK_MIN + 1) + ENEMY_ATTACK_MIN;
         playerHealth -= damage;
         System.out.println("The enemy hit you for " + damage + " damage!");
     }

BUILD A  Password Generator 

Here's a simple password generator application in Java.

This code generates a random password of a specified length with options to include uppercase letters, lowercase letters, digits, and special characters. You can customize the length and character set as needed.

import java.security.SecureRandom;

public class PasswordGenerator {
     private static final String UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
     private static final String LOWER = "abcdefghijklmnopqrstuvwxyz";
     private static final String DIGITS = "0123456789";
     private static final String SPECIAL = "!@#$%^&*()-_=+";

     public static void main(String[] args) {
         int length = 12; // Default password length
         boolean includeUpper = true;
         boolean includeLower = true;
         boolean includeDigits = true;
         boolean includeSpecial = true;

         String password = generatePassword(length, includeUpper, includeLower, includeDigits, includeSpecial);
         System.out.println("Generated Password: " + password);
     }

     public static String generatePassword(int length, boolean includeUpper, boolean includeLower, boolean includeDigits, boolean includeSpecial) {
         StringBuilder password = new StringBuilder();
         SecureRandom random = new SecureRandom();

         String characters = "";
         if (includeUpper) characters += UPPER;
         if (includeLower) characters += LOWER;
         if (includeDigits) characters += DIGITS;
         if (includeSpecial) characters += SPECIAL;

         for (int i = 0; i < length; i++) {
             int randomIndex = random.nextInt(characters.length());
             password.append(characters.charAt(randomIndex));
         }

         return password.toString();
     }

BUILD A  Reverse User Input 

Here's a simple Java application that reverses user input.

This program prompts the user to enter a string, reads the input, and then reverses the string using the 'reverseString' method. Finally, it prints the reversed string to the console.

import java.util.Scanner;

public class StringReversal {
     public static void main(String[] args) {
         Scanner scanner = new Scanner(System.in);

         System.out.print("Enter a string: ");
         String input = scanner.nextLine();

         String reversed = reverseString(input);

         System.out.println("Reversed string: " + reversed);

         scanner.close();
     }

         public static String reverseString(String input) {
         StringBuilder reversed = new StringBuilder();

         // Iterate over the input string in reverse order and append each character to the StringBuilder
         for (int i = input.length() - 1; i >= 0; i--) {
             reversed.append(input.charAt(i));
         }

         return reversed.toString();
     }