0% found this document useful (0 votes)
12 views

Java Programming Challenges

Uploaded by

RAKSHITH REDDY
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Java Programming Challenges

Uploaded by

RAKSHITH REDDY
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Java Programming Challenges

generate me a moderate level of programs in java

Here are a few moderate-level Java programming challenges that cover a variety of concepts,
including data structures, algorithms, and object-oriented programming principles:

1. Palindrome Checker Using Recursion


Write a program that checks if a given string is a palindrome using recursion. A palindrome is
a word or phrase that reads the same backward as forward.

Requirements:

Implement a recursive method to check the palindrome.

Consider edge cases like ignoring spaces, punctuation, and case sensitivity.

java

public class PalindromeChecker {


public static boolean isPalindrome(String str) {
// Remove non-alphanumeric characters and convert to lowercase
str = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();

// Call the recursive method


return checkPalindrome(str, 0, str.length() - 1);
}

private static boolean checkPalindrome(String str, int left, int right) {


if (left >= right) {
return true;
}
if (str.charAt(left) != str.charAt(right)) {
return false;
}
return checkPalindrome(str, left + 1, right - 1);
}

public static void main(String[] args) {


String input = "A man, a plan, a canal, Panama";
System.out.println(isPalindrome(input) ? "Palindrome" : "Not a palindrome");

1/62
}
}

2. Implementing a Simple Banking System


Create a basic banking system using Object-Oriented Programming concepts. The system
should include classes for BankAccount , Customer , and the ability to perform operations
like deposit, withdrawal, and balance checking.

Requirements:

Use classes and objects.

Ensure that withdrawal operations are not allowed if the balance is insufficient.

java

class BankAccount {
private String accountNumber;
private double balance;

public BankAccount(String accountNumber, double balance) {


this.accountNumber = accountNumber;
this.balance = balance;
}

public void deposit(double amount) {


balance += amount;
System.out.println("Deposited: $" + amount);
}

public void withdraw(double amount) {


if (amount > balance) {
System.out.println("Insufficient funds.");
} else {
balance -= amount;
System.out.println("Withdrew: $" + amount);
}
}

public double getBalance() {


return balance;
}

2/62
}

class Customer {
private String name;
private BankAccount bankAccount;

public Customer(String name, BankAccount bankAccount) {


this.name = name;
this.bankAccount = bankAccount;
}

public void displayDetails() {


System.out.println("Customer Name: " + name);
System.out.println("Account Balance: $" + bankAccount.getBalance());
}
}

public class BankingSystem {


public static void main(String[] args) {
BankAccount account = new BankAccount("123456789", 1000.0);
Customer customer = new Customer("John Doe", account);

customer.displayDetails();
account.deposit(500);
account.withdraw(300);
customer.displayDetails();
}
}

3. Sorting Students by Grades Using Comparator


Write a program that sorts a list of students by their grades using the Comparator interface.

Requirements:

Implement a class Student with fields like name and grade .

Sort the students using a custom comparator.

java

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

3/62
import java.util.List;

class Student {
private String name;
private double grade;

public Student(String name, double grade) {


this.name = name;
this.grade = grade;
}

public String getName() {


return name;
}

public double getGrade() {


return grade;
}

@Override
public String toString() {
return name + ": " + grade;
}
}

public class StudentSort {


public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 88.5));
students.add(new Student("Bob", 92.3));
students.add(new Student("Charlie", 85.7));
students.add(new Student("David", 90.1));

// Sort students by grade in descending order


Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return Double.compare(s2.getGrade(), s1.getGrade());
}
});

// Display sorted list of students

4/62
for (Student student : students) {
System.out.println(student);
}
}
}

4. Sudoku Validator
Create a program that validates whether a given 9x9 Sudoku puzzle solution is correct.

Requirements:

Check if each row, column, and 3x3 sub-grid contains digits 1 to 9 with no repetition.

Use data structures like sets to efficiently check for duplicates.

java

import java.util.HashSet;

public class SudokuValidator {


public static boolean isValidSudoku(int[][] board) {
for (int i = 0; i < 9; i++) {
HashSet<Integer> rows = new HashSet<>();
HashSet<Integer> columns = new HashSet<>();
HashSet<Integer> box = new HashSet<>();

for (int j = 0; j < 9; j++) {


// Check row
if (board[i][j] != 0 && !rows.add(board[i][j])) {
return false;
}

// Check column
if (board[j][i] != 0 && !columns.add(board[j][i])) {
return false;
}

// Check 3x3 sub-grid


int rowIndex = 3 * (i / 3) + j / 3;
int colIndex = 3 * (i % 3) + j % 3;
if (board[rowIndex][colIndex] != 0 && !box.add(board[rowIndex]
[colIndex])) {
return false;

5/62
}
}
}
return true;
}

public static void main(String[] args) {


int[][] sudokuBoard = {
{5, 3, 4, 6, 7, 8, 9, 1, 2},
{6, 7, 2, 1, 9, 5, 3, 4, 8},
{1, 9, 8, 3, 4, 2, 5, 6, 7},
{8, 5, 9, 7, 6, 1, 4, 2, 3},
{4, 2, 6, 8, 5, 3, 7, 9, 1},
{7, 1, 3, 9, 2, 4, 8, 5, 6},
{9, 6, 1, 5, 3, 7, 2, 8, 4},
{2, 8, 7, 4, 1, 9, 6, 3, 5},
{3, 4, 5, 2, 8, 6, 1, 7, 9}
};

System.out.println(isValidSudoku(sudokuBoard) ? "Valid Sudoku" : "Invalid


Sudoku");
}
}

These programs help to enhance your understanding of various concepts in Java, including
recursion, object-oriented programming, data structures, and the use of collections.

generate around 50 programs

Here’s a list of 50 Java programming exercises, covering various topics like data structures,
algorithms, OOP concepts, and general programming skills. Each program includes a brief
description of its functionality:

Basic Programs
1. Hello World: Print "Hello, World!" to the console.

2. Even or Odd: Check if a number is even or odd.

3. Prime Number Checker: Determine if a number is prime.

4. Factorial Calculation: Calculate the factorial of a number using recursion.

5. Fibonacci Series: Print the Fibonacci series up to a given number.

6/62
6. Sum of Digits: Calculate the sum of digits of a number.

7. Reverse a String: Reverse a given string.

8. Count Vowels and Consonants: Count the number of vowels and consonants in a string.

9. Temperature Converter: Convert Celsius to Fahrenheit and vice versa.

10. Basic Calculator: Implement a basic calculator for addition, subtraction, multiplication,
and division.

Intermediate Programs
11. Palindrome Checker: Check if a string is a palindrome.

12. Armstrong Number Checker: Check if a number is an Armstrong number.

13. Binary Search: Implement binary search on a sorted array.

14. Bubble Sort: Implement the bubble sort algorithm.

15. Selection Sort: Implement the selection sort algorithm.

16. Insertion Sort: Implement the insertion sort algorithm.

17. Merge Two Arrays: Merge two sorted arrays into one.

18. Matrix Addition: Add two matrices.

19. Transpose of a Matrix: Find the transpose of a given matrix.

20. String Permutations: Generate all permutations of a string.

Advanced Programs
21. Simple Banking System: Create a banking system with classes for BankAccount and
Customer .

22. Sudoku Validator: Validate a 9x9 Sudoku board.

23. Tic-Tac-Toe Game: Implement a simple text-based Tic-Tac-Toe game.

24. Library Management System: Create a library management system with options to add,
remove, and view books.

25. Shopping Cart: Implement a shopping cart system with add, remove, and checkout
functionality.

26. Employee Management System: Create an employee management system using


classes and objects.

7/62
27. Student Grade Management: Manage student grades and calculate averages using a
class.

28. Maze Solver: Use recursion to find a path through a maze.

29. Word Count in a File: Count the number of words in a text file.

30. File Encryption/Decryption: Implement a simple file encryption and decryption method.

Data Structure Programs


31. Linked List Implementation: Implement a singly linked list.

32. Stack Implementation: Implement a stack using arrays or linked list.

33. Queue Implementation: Implement a queue using arrays or linked list.

34. Binary Tree Traversal: Implement pre-order, in-order, and post-order traversal for a
binary tree.

35. HashMap Implementation: Create a simple hash map with put and get methods.

36. Priority Queue Implementation: Implement a priority queue using a heap.

37. Graph Representation: Represent a graph using adjacency list and perform depth-first
search (DFS).

38. Dynamic Array Implementation: Implement a dynamic array that resizes as needed.

39. Circular Linked List: Implement a circular linked list with basic operations.

40. Trie Implementation: Implement a trie for efficient string search.

Miscellaneous Programs
41. Simple To-Do List: Create a console-based to-do list application.

42. Hangman Game: Implement a simple text-based Hangman game.

43. Currency Converter: Create a currency converter with static conversion rates.

44. Recipe Manager: Create a simple application to manage recipes (add, view, delete).

45. Simple Chat Application: Create a console-based chat application using sockets.

46. Weather Information Fetcher: Fetch and display weather information from an API.

47. Palindrome Linked List Checker: Check if a linked list is a palindrome.

48. XML Parser: Create a simple XML parser to extract data from an XML file.

49. Online Voting System: Implement a simple online voting system.

8/62
50. Personal Diary Application: Create a console application to manage diary entries.

Tips for Implementation


Start with the simpler problems and gradually work your way to the more complex ones.

Focus on clean code, proper naming conventions, and commenting for better
readability.

Use version control (like Git) to track your progress and changes.

Explore different data structures and algorithms as you implement these programs.

Test your programs thoroughly to handle various edge cases.

If you need any specific implementation or help with a particular program, feel free to ask!

generate code

Here are implementations for a selection of the programs from the list of 50 Java
programming exercises. I've chosen a mix of basic, intermediate, and advanced programs to
showcase various concepts:

1. Hello World

java

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

2. Even or Odd

java

import java.util.Scanner;

public class EvenOrOdd {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();

9/62
System.out.println(number % 2 == 0 ? "Even" : "Odd");
}
}

3. Prime Number Checker

java

import java.util.Scanner;

public class PrimeChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
boolean isPrime = true;

for (int i = 2; i <= Math.sqrt(number); i++) {


if (number % i == 0) {
isPrime = false;
break;
}
}
System.out.println(isPrime ? "Prime" : "Not Prime");
}
}

4. Factorial Calculation

java

import java.util.Scanner;

public class Factorial {


public static int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");

10/62
int number = scanner.nextInt();
System.out.println("Factorial: " + factorial(number));
}
}

5. Fibonacci Series
java

import java.util.Scanner;

public class FibonacciSeries {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of terms: ");
int n = scanner.nextInt();
int a = 0, b = 1;

System.out.print("Fibonacci Series: ");


for (int i = 0; i < n; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
}
}

6. Reverse a String
java

import java.util.Scanner;

public class ReverseString {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
String reversed = new StringBuilder(input).reverse().toString();
System.out.println("Reversed string: " + reversed);

11/62
}
}

7. Palindrome Checker
java

import java.util.Scanner;

public class PalindromeChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
String reversed = new StringBuilder(input).reverse().toString();
System.out.println(input.equals(reversed) ? "Palindrome" : "Not a
palindrome");
}
}

8. Simple Banking System

java

import java.util.Scanner;

class BankAccount {
private String accountNumber;
private double balance;

public BankAccount(String accountNumber, double balance) {


this.accountNumber = accountNumber;
this.balance = balance;
}

public void deposit(double amount) {


balance += amount;
System.out.println("Deposited: $" + amount);
}

public void withdraw(double amount) {


if (amount > balance) {

12/62
System.out.println("Insufficient funds.");
} else {
balance -= amount;
System.out.println("Withdrew: $" + amount);
}
}

public double getBalance() {


return balance;
}
}

public class BankingSystem {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BankAccount account = new BankAccount("123456789", 1000.0);

while (true) {
System.out.println("\nOptions: 1. Deposit 2. Withdraw 3. Check Balance
4. Exit");
System.out.print("Choose an option: ");
int option = scanner.nextInt();

switch (option) {
case 1:
System.out.print("Enter amount to deposit: ");
account.deposit(scanner.nextDouble());
break;
case 2:
System.out.print("Enter amount to withdraw: ");
account.withdraw(scanner.nextDouble());
break;
case 3:
System.out.println("Balance: $" + account.getBalance());
break;
case 4:
System.exit(0);
default:
System.out.println("Invalid option.");
}
}

13/62
}
}

9. Simple To-Do List


java

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

public class TodoList {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> todoList = new ArrayList<>();
String input;

while (true) {
System.out.println("\nOptions: 1. Add Task 2. View Tasks 3. Exit");
System.out.print("Choose an option: ");
int option = scanner.nextInt();
scanner.nextLine(); // Consume newline

switch (option) {
case 1:
System.out.print("Enter task: ");
input = scanner.nextLine();
todoList.add(input);
System.out.println("Task added.");
break;
case 2:
System.out.println("To-Do List:");
for (String task : todoList) {
System.out.println("- " + task);
}
break;
case 3:
System.exit(0);
default:
System.out.println("Invalid option.");
}
}

14/62
}
}

10. Simple Chat Application (Server)


Server

java

import java.io.*;
import java.net.*;

public class SimpleChatServer {


public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(1234)) {
System.out.println("Chat server started...");
while (true) {
Socket socket = serverSocket.accept();
new ChatHandler(socket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

class ChatHandler extends Thread {


private Socket socket;

public ChatHandler(Socket socket) {


this.socket = socket;
}

public void run() {


try (BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true)) {

String message;
while ((message = input.readLine()) != null) {
System.out.println("Client: " + message);
output.println("Server: " + message);
}

15/62
} catch (IOException e) {
e.printStackTrace();
}
}
}

Client

java

import java.io.*;
import java.net.*;

public class SimpleChatClient {


public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 1234);
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
BufferedReader consoleInput = new BufferedReader(new
InputStreamReader(System.in))) {

String message;
System.out.println("Connected to chat server. Type your messages:");
while ((message = consoleInput.readLine()) != null) {
output.println(message);
System.out.println(input.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

These implementations provide a solid foundation for each program. Feel free to expand
upon them, modify features, or ask for more specific code implementations for any other
programs from the list!

continue

Sure! Here are more Java programs from the list, covering additional exercises and
expanding upon various topics:

16/62
11. Armstrong Number Checker

java

import java.util.Scanner;

public class ArmstrongNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int originalNumber = number;
int sum = 0;

while (number > 0) {


int digit = number % 10;
sum += digit * digit * digit; // For 3-digit numbers
number /= 10;
}

System.out.println(originalNumber == sum ? "Armstrong Number" : "Not an


Armstrong Number");
}
}

12. Binary Search


java

import java.util.Scanner;

public class BinarySearch {


public static int binarySearch(int[] arr, int key) {
int low = 0, high = arr.length - 1;

while (low <= high) {


int mid = (low + high) / 2;
if (arr[mid] == key) return mid;
else if (arr[mid] < key) low = mid + 1;
else high = mid - 1;
}
return -1; // Not found

17/62
}

public static void main(String[] args) {


int[] arr = {2, 5, 8, 12, 16, 23, 38, 45, 56, 72};
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number to search: ");
int key = scanner.nextInt();
int result = binarySearch(arr, key);
System.out.println(result == -1 ? "Element not found" : "Element found at
index: " + result);
}
}

13. Bubble Sort


java

import java.util.Arrays;

public class BubbleSort {


public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
int n = arr.length;

for (int i = 0; i < n - 1; i++) {


for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}

System.out.println("Sorted array: " + Arrays.toString(arr));


}
}

14. Merge Two Arrays

java

18/62
import java.util.Arrays;

public class MergeArrays {


public static void main(String[] args) {
int[] arr1 = {1, 3, 5};
int[] arr2 = {2, 4, 6};
int[] merged = new int[arr1.length + arr2.length];

int i = 0, j = 0, k = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
merged[k++] = arr1[i++];
} else {
merged[k++] = arr2[j++];
}
}

while (i < arr1.length) merged[k++] = arr1[i++];


while (j < arr2.length) merged[k++] = arr2[j++];

System.out.println("Merged array: " + Arrays.toString(merged));


}
}

15. Matrix Addition


java

import java.util.Scanner;

public class MatrixAddition {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int rows, cols;

System.out.print("Enter number of rows: ");


rows = scanner.nextInt();
System.out.print("Enter number of columns: ");
cols = scanner.nextInt();

int[][] matrix1 = new int[rows][cols];

19/62
int[][] matrix2 = new int[rows][cols];
int[][] sum = new int[rows][cols];

System.out.println("Enter elements of first matrix:");


for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix1[i][j] = scanner.nextInt();

System.out.println("Enter elements of second matrix:");


for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix2[i][j] = scanner.nextInt();

for (int i = 0; i < rows; i++)


for (int j = 0; j < cols; j++)
sum[i][j] = matrix1[i][j] + matrix2[i][j];

System.out.println("Sum of matrices:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++)
System.out.print(sum[i][j] + " ");
System.out.println();
}
}
}

16. String Permutations


java

import java.util.Scanner;

public class StringPermutations {


public static void permute(String str, String perm) {
if (str.isEmpty()) {
System.out.println(perm);
} else {
for (int i = 0; i < str.length(); i++) {
permute(str.substring(0, i) + str.substring(i + 1), perm +
str.charAt(i));
}
}

20/62
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
System.out.println("Permutations of the string:");
permute(input, "");
}
}

17. Simple Chat Application (with GUI)


For a simple GUI-based chat application, we can use Swing. Here's an example of a basic chat
client.

Chat Client GUI

java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

public class ChatClientGUI {


private Socket socket;
private PrintWriter out;
private JTextArea textArea;
private JTextField textField;

public ChatClientGUI() {
JFrame frame = new JFrame("Chat Client");
textArea = new JTextArea(20, 50);
textField = new JTextField(50);
textArea.setEditable(false);
frame.add(new JScrollPane(textArea), BorderLayout.CENTER);
frame.add(textField, BorderLayout.SOUTH);

textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendMessage();

21/62
}
});

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);

try {
socket = new Socket("localhost", 1234);
out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
String message;
while ((message = in.readLine()) != null) {
textArea.append("Server: " + message + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}

private void sendMessage() {


String message = textField.getText();
out.println(message);
textArea.append("You: " + message + "\n");
textField.setText("");
}

public static void main(String[] args) {


new ChatClientGUI();
}
}

18. Employee Management System

java

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

class Employee {
private String name;

22/62
private int id;

public Employee(String name, int id) {


this.name = name;
this.id = id;
}

public String getName() {


return name;
}

public int getId() {


return id;
}

@Override
public String toString() {
return "ID: " + id + ", Name: " + name;
}
}

public class EmployeeManagement {


public static void main(String[] args) {
ArrayList<Employee> employees = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
int option;

while (true) {
System.out.println("\nOptions: 1. Add Employee 2. View Employees 3.
Exit");
System.out.print("Choose an option: ");
option = scanner.nextInt();
scanner.nextLine(); // Consume newline

switch (option) {
case 1:
System.out.print("Enter employee name: ");
String name = scanner.nextLine();
System.out.print("Enter employee ID: ");
int id = scanner.nextInt();
employees.add(new Employee(name, id));
System.out.println("Employee added.");

23/62
break;
case 2:
System.out.println("Employees:");
for (Employee emp : employees) {
System.out.println(emp);
}
break;
case 3:
System.exit(0);
default:
System.out.println("Invalid option.");
}
}
}
}

19. Simple Library Management System

java

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

class Book {
private String title;

public Book(String title) {


this.title = title;
}

public String getTitle() {


return title;
}

@Override
public String toString() {
return title;
}
}

public class LibraryManagement {


public static void main(String[] args) {

24/62
ArrayList<Book> books = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
int option;

while (true) {
System.out.println("\nOptions: 1. Add Book 2. View Books 3. Exit");
System.out.print("Choose an option: ");
option = scanner.nextInt();
scanner.nextLine(); // Consume newline

switch (option) {
case 1:
System.out.print("Enter book title: ");
String title = scanner.nextLine();
books.add(new Book(title));
System.out.println("Book added.");
break;
case 2:
System.out.println("Books:");
for (Book book : books) {
System.out.println(book);
}
break;
case 3:
System.exit(0);
default:
System.out.println("Invalid option.");
}
}
}
}

20. Simple Quiz Application

java

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

public class QuizApplication {


public static void main(String[] args) {

25/62
HashMap<String, String> questions = new HashMap<>();
questions.put("What is the capital of France?", "Paris");
questions.put("What is 2 + 2?", "4");
questions.put("What is the capital of Japan?", "Tokyo");

Scanner scanner = new Scanner(System.in);


int score = 0;

for (Map.Entry<String, String> entry : questions.entrySet()) {


System.out.println(entry.getKey());
String answer = scanner.nextLine();
if (answer.equalsIgnoreCase(entry.getValue())) {
score++;
System.out.println("Correct!");
} else {
System.out.println("Wrong! The correct answer is: " +
entry.getValue());
}
}

System.out.println("Your score: " + score + "/" + questions.size());


}
}

Feel free to run these Java programs to see how they work and modify them as needed. If
you need any further explanations or more examples, let me know!

continue

Here are more Java programs to continue the list, focusing on different topics and concepts:

21. Fibonacci Series

java

import java.util.Scanner;

public class FibonacciSeries {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of terms in Fibonacci series: ");
int n = scanner.nextInt();
int a = 0, b = 1;

26/62
System.out.print("Fibonacci Series: ");
for (int i = 1; i <= n; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
}
}

22. Prime Number Checker

java

import java.util.Scanner;

public class PrimeNumberChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
boolean isPrime = true;

for (int i = 2; i <= Math.sqrt(number); i++) {


if (number % i == 0) {
isPrime = false;
break;
}
}

System.out.println(number + (isPrime ? " is a prime number." : " is not a


prime number."));
}
}

23. Palindrome Checker


java

import java.util.Scanner;

27/62
public class PalindromeChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
String reversed = new StringBuilder(str).reverse().toString();

System.out.println(str + (str.equals(reversed) ? " is a palindrome." : " is


not a palindrome."));
}
}

24. Simple Calculator


java

import java.util.Scanner;

public class SimpleCalculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();

System.out.print("Choose an operation (+, -, *, /): ");


char operation = scanner.next().charAt(0);
double result;

switch (operation) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {

28/62
result = num1 / num2;
} else {
System.out.println("Division by zero is not allowed.");
return;
}
break;
default:
System.out.println("Invalid operation.");
return;
}

System.out.println("Result: " + result);


}
}

25. Find the Largest Element in an Array


java

import java.util.Scanner;

public class LargestElement {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter the elements:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

int largest = arr[0];


for (int i = 1; i < n; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}

System.out.println("Largest element: " + largest);

29/62
}
}

26. Count Vowels and Consonants in a String

java

import java.util.Scanner;

public class CountVowelsConsonants {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine().toLowerCase();
int vowels = 0, consonants = 0;

for (char ch : str.toCharArray()) {


if (Character.isLetter(ch)) {
if ("aeiou".indexOf(ch) != -1) {
vowels++;
} else {
consonants++;
}
}
}

System.out.println("Vowels: " + vowels + ", Consonants: " + consonants);


}
}

27. Count the Number of Words in a String

java

import java.util.Scanner;

public class CountWords {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = scanner.nextLine();
String[] words = sentence.trim().split("\\s+");

30/62
System.out.println("Number of words: " + words.length);
}
}

28. Factorial of a Number (Using Recursion)


java

import java.util.Scanner;

public class Factorial {


public static int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
System.out.println("Factorial of " + number + " is: " + factorial(number));
}
}

29. Implementing a Basic Stopwatch


java

import java.util.Scanner;

public class Stopwatch {


public static void main(String[] args) throws InterruptedException {
Scanner scanner = new Scanner(System.in);
System.out.print("Press Enter to start the stopwatch...");
scanner.nextLine();
long startTime = System.currentTimeMillis();

System.out.print("Press Enter again to stop the stopwatch...");


scanner.nextLine();
long endTime = System.currentTimeMillis();

31/62
long elapsedTime = endTime - startTime;
System.out.println("Elapsed Time: " + (elapsedTime / 1000.0) + " seconds");
}
}

30. Simple To-Do List Application

java

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

public class ToDoList {


public static void main(String[] args) {
ArrayList<String> toDoList = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
int option;

while (true) {
System.out.println("\nOptions: 1. Add Task 2. View Tasks 3. Exit");
System.out.print("Choose an option: ");
option = scanner.nextInt();
scanner.nextLine(); // Consume newline

switch (option) {
case 1:
System.out.print("Enter task: ");
String task = scanner.nextLine();
toDoList.add(task);
System.out.println("Task added.");
break;
case 2:
System.out.println("Tasks:");
for (String t : toDoList) {
System.out.println(t);
}
break;
case 3:
System.exit(0);
default:
System.out.println("Invalid option.");
}

32/62
}
}
}

31. Checking for Anagrams


java

import java.util.Arrays;
import java.util.Scanner;

public class AnagramChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first string: ");
String str1 = scanner.nextLine().replaceAll("\\s+", "").toLowerCase();
System.out.print("Enter second string: ");
String str2 = scanner.nextLine().replaceAll("\\s+", "").toLowerCase();

char[] arr1 = str1.toCharArray();


char[] arr2 = str2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);

boolean isAnagram = Arrays.equals(arr1, arr2);


System.out.println("The strings are " + (isAnagram ? "anagrams." : "not
anagrams."));
}
}

32. Convert Temperature from Celsius to Fahrenheit

java

import java.util.Scanner;

public class TemperatureConverter {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter temperature in Celsius: ");
double celsius = scanner.nextDouble();
double fahrenheit = (celsius * 9/5) + 32;

33/62
System.out.println("Temperature in Fahrenheit: " + fahrenheit);
}
}

33. Sum of Natural Numbers

java

import java.util.Scanner;

public class SumOfNaturalNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int n = scanner.nextInt();
int sum = n * (n + 1) / 2; // Formula for sum of first n natural numbers
System.out.println("Sum of natural numbers up to " + n + ": " + sum);
}
}

34. Remove Duplicate Elements from an Array


java

import java.util.Arrays;
import java.util.HashSet;

public class RemoveDuplicates {


public static void main(String[] args) {
int[] arr = {1, 2, 2, 3, 4, 4, 5};
HashSet<Integer> set = new HashSet<>();

for (int num : arr) {


set.add(num);
}

System.out.println("Array after removing duplicates: " + set);


}
}

35. Number Guessing Game

34/62
java

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

public class NumberGuessingGame {


public static void main(String[] args) {
Random random = new Random();
int numberToGuess = random.nextInt(100) + 1;
Scanner scanner = new Scanner(System.in);
int guess;
int attempts = 0;

do {
System.out.print("Guess the number (1-100): ");
guess = scanner.nextInt();
attempts++;

if (guess < numberToGuess) {


System.out.println("Higher!");
} else if (guess > numberToGuess) {
System.out.println("Lower!");
} else {
System.out.println("Correct! You guessed it in " + attempts + "
attempts.");
}
} while (guess != numberToGuess);
}
}

36. Reverse a String


java

import java.util.Scanner;

public class ReverseString {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
String reversed = new StringBuilder(str).reverse().toString();

35/62
System.out.println("Reversed String: " + reversed);
}
}

37. Basic Bank Account Management


java

import java.util.Scanner;

class BankAccount {
private String accountHolder;
private double balance;

public BankAccount(String accountHolder) {


this.accountHolder = accountHolder;
this.balance = 0.0;
}

public void deposit(double amount) {


balance += amount;
System.out.println("Deposited: " + amount);
}

public void withdraw(double amount) {


if (amount <= balance) {
balance -= amount;
System.out.println("Withdrew: " + amount);
} else {
System.out.println("Insufficient balance.");
}
}

public void displayBalance() {


System.out.println("Balance: " + balance);
}
}

public class BankAccountManagement {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter account holder's name: ");

36/62
String name = scanner.nextLine();
BankAccount account = new BankAccount(name);

int option;
do {
System.out.println("\nOptions: 1. Deposit 2. Withdraw 3. Check Balance
4. Exit");
option = scanner.nextInt();

switch (option) {
case 1:
System.out.print("Enter amount to deposit: ");
double depositAmount = scanner.nextDouble();
account.deposit(depositAmount);
break;
case 2:
System.out.print("Enter amount to withdraw: ");
double withdrawAmount = scanner.nextDouble();
account.withdraw(withdrawAmount);
break;
case 3:
account.displayBalance();
break;
case 4:
System.out.println("Exiting.");
break;
default:
System.out.println("Invalid option.");
}
} while (option != 4);
}
}

38. Binary to Decimal Converter

java

import java.util.Scanner;

public class BinaryToDecimal {


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

37/62
System.out.print("Enter a binary number: ");
String binaryString = scanner.nextLine();
int decimal = Integer.parseInt(binaryString, 2);
System.out.println("Decimal value: " + decimal);
}
}

39. Decimal to Binary Converter

java

import java.util.Scanner;

public class DecimalToBinary {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
int decimal = scanner.nextInt();
String binary = Integer.toBinaryString(decimal);
System.out.println("Binary value: " + binary);
}
}

40. Sum of Digits in a Number

java

import java.util.Scanner;

public class SumOfDigits {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int sum = 0;

while (number != 0) {
sum += number % 10;
number /= 10;
}

System.out.println("Sum of digits: " + sum);

38/62
}
}

41. Character Frequency in a String

java

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

public class CharacterFrequency {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
HashMap<Character, Integer> frequencyMap = new HashMap<>();

for (char ch : str.toCharArray()) {


frequencyMap.put(ch, frequencyMap.getOrDefault(ch, 0) + 1);
}

System.out.println("Character Frequencies: " + frequencyMap);


}
}

42. Simple Voting System

java

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

public class VotingSystem {


public static void main(String[] args) {
HashMap<String, Integer> candidates = new HashMap<>();
candidates.put("Candidate A", 0);
candidates.put("Candidate B", 0);
candidates.put("Candidate C", 0);

Scanner scanner = new Scanner(System.in);


String vote;

39/62
while (true) {
System.out.print("Vote for a candidate (A/B/C or Exit to finish): ");
vote = scanner.nextLine().toUpperCase();
if (vote.equals("EXIT")) {
break;
}
switch (vote) {
case "A":
candidates.put("Candidate A", candidates.get("Candidate A") +
1);
break;
case "B":
candidates.put("Candidate B", candidates.get("Candidate B") +
1);
break;
case "C":
candidates.put("Candidate C", candidates.get("Candidate C") +
1);
break;
default:
System.out.println("Invalid vote.");
}
}

System.out.println("Voting Results:");
for (Map.Entry<String, Integer> entry : candidates.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue() + " votes");
}
}
}

43. Simple Tic-Tac-Toe Game

java

import java.util.Scanner;

public class TicTacToe {


private static char[][] board = {{' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', '
'}};
private static char currentPlayer = 'X';

40/62
public static void main(String[] args) {
while (true) {
printBoard();
playerMove();
if (checkWin()) {
printBoard();
System.out.println("Player " + currentPlayer + " wins!");
break;
}
if (isBoardFull()) {
printBoard();
System.out.println("It's a draw!");
break;
}
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
}

private static void printBoard() {


System.out.println("Current board:");
for (char[] row : board) {
for (char cell : row) {
System.out.print(cell + "|");
}
System.out.println();
}
}

private static void playerMove() {


Scanner scanner = new Scanner(System.in);
int row, col;
while (true) {
System.out.print("Player " + currentPlayer + ", enter row (0-2) and
column (0-2): ");
row = scanner.nextInt();
col = scanner.nextInt();
if (row >= 0 && row < 3 && col >= 0 && col < 3 && board[row][col] == '
') {
board[row][col] = currentPlayer;
break;
} else {
System.out.println("This move is not valid. Try again.");

41/62
}
}
}

private static boolean checkWin() {


for (int i = 0; i < 3; i++) {
if (board[i][0] == currentPlayer && board[i][1] == currentPlayer &&
board[i][2] == currentPlayer) {
return true;
}
if (board[0][i] == currentPlayer && board[1][i] == currentPlayer &&
board[2][i] == currentPlayer) {
return true;
}
}
return (board[0][0] == currentPlayer && board[1][1] == currentPlayer &&
board[2][2] == currentPlayer) ||
(board[0][2] == currentPlayer && board[1][1] == currentPlayer &&
board[2][0] == currentPlayer);
}

private static boolean isBoardFull() {


for (char[] row : board) {
for (char cell : row) {
if (cell == ' ') {
return false;
}
}
}
return true;
}
}

44. Simple Password Validation

java

import java.util.Scanner;

public class PasswordValidator {


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

42/62
System.out.print("Enter a password: ");
String password = scanner.nextLine();

if (isValidPassword(password)) {
System.out.println("Password is valid.");
} else {
System.out.println("Password must be at least 8 characters long and
contain at least one digit and one uppercase letter.");
}
}

public static boolean isValidPassword(String password) {


return password.length() >= 8 && password.matches(".*[0-9].*") &&
password.matches(".*[A-Z].*");
}
}

45. Simple Interest Calculator

java

import java.util.Scanner;

public class SimpleInterestCalculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter principal amount: ");
double principal = scanner.nextDouble();
System.out.print("Enter rate of interest: ");
double rate = scanner.nextDouble();
System.out.print("Enter time (in years): ");
double time = scanner.nextDouble();

double simpleInterest = (principal * rate * time) / 100;


System.out.println("Simple Interest: " + simpleInterest);
}
}

46. Leap Year Checker

java

43/62
import java.util.Scanner;

public class LeapYearChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = scanner.nextInt();

if (isLeapYear(year)) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
}

public static boolean isLeapYear(int year) {


return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
}

47. Prime Number Checker


java

import java.util.Scanner;

public class PrimeNumberChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();

if (isPrime(number)) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
}

public static boolean isPrime(int number) {


if (number <= 1) return false;

44/62
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) return false;
}
return true;
}
}

48. Fibonacci Series Generator


java

import java.util.Scanner;

public class FibonacciSeries {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of terms in the Fibonacci series: ");
int n = scanner.nextInt();
int a = 0, b = 1;

System.out.print("Fibonacci Series: ");


for (int i = 1; i <= n; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
}
}

49. Factorial Calculator

java

import java.util.Scanner;

public class FactorialCalculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
long factorial = calculateFactorial(number);

45/62
System.out.println("Factorial of " + number + " is: " + factorial);
}

public static long calculateFactorial(int number) {


long result = 1;
for (int i = 1; i <= number; i++) {
result *= i;
}
return result;
}
}

50. Simple Calendar


java

import java.util.Calendar;
import java.util.Scanner;

public class SimpleCalendar {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter year: ");
int year = scanner.nextInt();
System.out.print("Enter month (1-12): ");
int month = scanner.nextInt();

Calendar calendar = Calendar.getInstance();


calendar.set(year, month - 1, 1);
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

System.out.println("Days in month: " + daysInMonth);


}
}

51. Simple Maze Solver


java

public class MazeSolver {


public static void main(String[] args) {
int[][] maze = {

46/62
{0, 0, 0, 0, 0},
{1, 1, 0, 1, 0},
{0, 1, 0, 1, 0},
{0, 1, 0, 0, 0},
{0, 0, 0, 1, 0}
};

if (solveMaze(maze, 0, 0)) {
System.out.println("Path exists in the maze.");
} else {
System.out.println("No path exists in the maze.");
}
}

public static boolean solveMaze(int[][] maze, int x, int y) {


if (x == maze.length - 1 && y == maze[0].length - 1) {
return true; // Reached destination
}
if (isSafe(maze, x, y)) {
if (solveMaze(maze, x + 1, y)) {
return true;
}
if (solveMaze(maze, x, y + 1)) {
return true;
}
}
return false;
}

public static boolean isSafe(int[][] maze, int x, int y) {


return (x >= 0 && x < maze.length && y >= 0 && y < maze[0].length && maze[x]
[y] == 0);
}
}

These additional programs cover various topics and concepts in Java, including algorithms,
data structures, and basic game mechanics. Let me know if you need more programs or
explanations!

continue

Sure! Here are more Java programs that cover different concepts and functionalities:

47/62
52. Palindrome Checker
java

import java.util.Scanner;

public class PalindromeChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
if (isPalindrome(str)) {
System.out.println(str + " is a palindrome.");
} else {
System.out.println(str + " is not a palindrome.");
}
}

public static boolean isPalindrome(String str) {


String reversed = new StringBuilder(str).reverse().toString();
return str.equals(reversed);
}
}

53. Merge Two Sorted Arrays


java

import java.util.Arrays;

public class MergeSortedArrays {


public static void main(String[] args) {
int[] array1 = {1, 3, 5, 7};
int[] array2 = {2, 4, 6, 8};
int[] mergedArray = mergeArrays(array1, array2);
System.out.println("Merged Array: " + Arrays.toString(mergedArray));
}

public static int[] mergeArrays(int[] array1, int[] array2) {


int[] merged = new int[array1.length + array2.length];
int i = 0, j = 0, k = 0;
while (i < array1.length && j < array2.length) {

48/62
if (array1[i] < array2[j]) {
merged[k++] = array1[i++];
} else {
merged[k++] = array2[j++];
}
}
while (i < array1.length) {
merged[k++] = array1[i++];
}
while (j < array2.length) {
merged[k++] = array2[j++];
}
return merged;
}
}

54. Count Vowels in a String


java

import java.util.Scanner;

public class VowelCounter {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
int vowelCount = countVowels(str);
System.out.println("Number of vowels: " + vowelCount);
}

public static int countVowels(String str) {


int count = 0;
for (char ch : str.toLowerCase().toCharArray()) {
if ("aeiou".indexOf(ch) != -1) {
count++;
}
}
return count;
}
}

49/62
55. Find the Largest Element in an Array

java

import java.util.Scanner;

public class LargestElement {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] array = new int[n];

System.out.println("Enter the elements:");


for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}

int largest = findLargest(array);


System.out.println("Largest element: " + largest);
}

public static int findLargest(int[] array) {


int max = array[0];
for (int num : array) {
if (num > max) {
max = num;
}
}
return max;
}
}

56. Remove All Whitespaces from a String


java

import java.util.Scanner;

public class RemoveWhitespaces {


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

50/62
System.out.print("Enter a string: ");
String str = scanner.nextLine();
String result = removeWhitespaces(str);
System.out.println("String without whitespaces: " + result);
}

public static String removeWhitespaces(String str) {


return str.replaceAll("\\s+", "");
}
}

57. Sort an Array in Ascending Order


java

import java.util.Arrays;
import java.util.Scanner;

public class SortArray {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] array = new int[n];

System.out.println("Enter the elements:");


for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}

Arrays.sort(array);
System.out.println("Sorted array: " + Arrays.toString(array));
}
}

58. Simple Quiz Application


java

import java.util.Scanner;

public class QuizApplication {

51/62
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] questions = {
"What is the capital of France? (a) Paris (b) London (c) Berlin",
"What is 2 + 2? (a) 3 (b) 4 (c) 5"
};
char[] answers = {'a', 'b'};
int score = 0;

for (int i = 0; i < questions.length; i++) {


System.out.println(questions[i]);
char userAnswer = scanner.next().charAt(0);
if (userAnswer == answers[i]) {
score++;
}
}

System.out.println("Your score: " + score + "/" + questions.length);


}
}

59. Basic String Manipulations


java

import java.util.Scanner;

public class StringManipulation {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();

System.out.println("Length: " + str.length());


System.out.println("Uppercase: " + str.toUpperCase());
System.out.println("Lowercase: " + str.toLowerCase());
System.out.println("Reversed: " + new
StringBuilder(str).reverse().toString());
}
}

52/62
60. Simple To-Do List Application

java

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

public class ToDoList {


public static void main(String[] args) {
ArrayList<String> tasks = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
int option;

do {
System.out.println("1. Add Task 2. View Tasks 3. Exit");
option = scanner.nextInt();
scanner.nextLine(); // Consume newline

switch (option) {
case 1:
System.out.print("Enter a task: ");
String task = scanner.nextLine();
tasks.add(task);
break;
case 2:
System.out.println("Tasks:");
for (String t : tasks) {
System.out.println(t);
}
break;
case 3:
System.out.println("Exiting.");
break;
default:
System.out.println("Invalid option.");
}
} while (option != 3);
}
}

61. Temperature Converter

53/62
java

import java.util.Scanner;

public class TemperatureConverter {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter temperature in Celsius: ");
double celsius = scanner.nextDouble();
double fahrenheit = convertCelsiusToFahrenheit(celsius);
System.out.println("Temperature in Fahrenheit: " + fahrenheit);
}

public static double convertCelsiusToFahrenheit(double celsius) {


return (celsius * 9/5) + 32;
}
}

62. Simple Email Validator


java

import java.util.Scanner;

public class EmailValidator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an email address: ");
String email = scanner.nextLine();
if (isValidEmail(email)) {
System.out.println("Valid email address.");
} else {
System.out.println("Invalid email address.");
}
}

public static boolean isValidEmail(String email) {


return email.contains("@") && email.contains(".");
}
}

63. Simple Stopwatch

54/62
java

import java.util.Scanner;

public class SimpleStopwatch {


public static void main(String[] args) throws InterruptedException {
Scanner scanner = new Scanner(System.in);
System.out.print("Press Enter to start the stopwatch...");
scanner.nextLine();
long startTime = System.currentTimeMillis();

System.out.print("Press Enter to stop the stopwatch...");


scanner.nextLine();
long endTime = System.currentTimeMillis();

long elapsedTime = endTime - startTime;


System.out.println("Elapsed time in seconds: " + (elapsedTime / 1000.0));
}
}

64. Basic Shopping Cart System


java

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

public class ShoppingCart {


public static void main(String[] args) {
ArrayList<String> cart = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
String item;
int option;

do {
System.out.println("1. Add Item 2. View Cart 3. Exit");
option = scanner.nextInt();
scanner.nextLine(); // Consume newline

switch (option) {
case 1:
System.out.print("Enter item name: ");

55/62
item = scanner.nextLine();
cart.add(item);
break;
case 2:
System.out.println("Items in cart:");
for (String cartItem : cart) {
System.out.println(cartItem);
}
break;
case 3:
System.out.println("Exiting.");
break;
default:
System.out.println("Invalid option.");
}
} while (option != 3);
}
}

65. Simple Text-Based Adventure Game


java

import java.util.Scanner;

public class AdventureGame {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the Adventure Game!");
System.out.println("You are in a dark forest. You can go left or right.");

String choice = scanner.nextLine();

if (choice.equalsIgnoreCase("left")) {
System.out.println("You encounter a friendly elf who gives you a
treasure.");
} else if (choice.equalsIgnoreCase("right")) {
System.out.println("You encounter a scary monster and run away!");
} else {
System.out.println("Invalid choice. The game ends.");
}

56/62
}
}

66. Simple Budget Tracker


java

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

public class BudgetTracker {


public static void main(String[] args) {
ArrayList<Double> expenses = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
double expense;
int option;

do {
System.out.println("1. Add Expense 2. View Expenses 3. Exit");
option = scanner.nextInt();

switch (option) {
case 1:
System.out.print("Enter expense amount: ");
expense = scanner.nextDouble();
expenses.add(expense);
break;
case 2:
System.out.println("Expenses:");
for (double e : expenses) {
System.out.println(e);
}
break;
case 3:
System.out.println("Exiting.");
break;
default:
System.out.println("Invalid option.");
}
} while (option != 3);

57/62
}
}

67. URL Shortener (Mock)

java

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

public class URLShortener {


private static HashMap<String, String> urlMap = new HashMap<>();
private static int idCounter = 0;

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
String option;

do {
System.out.print("Enter a URL to shorten (or 'exit' to quit): ");
String url = scanner.nextLine();
if (url.equalsIgnoreCase("exit")) break;

String shortUrl = shortenUrl(url);


System.out.println("Shortened URL: " + shortUrl);
} while (true);
}

public static String shortenUrl(String url) {


String shortUrl = "short.ly/" + (idCounter++);
urlMap.put(shortUrl, url);
return shortUrl;
}
}

68. Simple Guessing Game


java

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

58/62
public class GuessingGame {
public static void main(String[] args) {
Random random = new Random();
int numberToGuess = random.nextInt(100) + 1;
int guess;
Scanner scanner = new Scanner(System.in);

System.out.println("Guess a number between 1 and 100:");

do {
guess = scanner.nextInt();
if (guess < numberToGuess) {
System.out.println("Too low! Try again.");
} else if (guess > numberToGuess) {
System.out.println("Too high! Try again.");
} else {
System.out.println("Congratulations! You've guessed the number!");
}
} while (guess != numberToGuess);
}
}

69. Simple Bank Account System


java

import java.util.Scanner;

public class BankAccount {


private double balance;

public BankAccount() {
this.balance = 0.0;
}

public void deposit(double amount) {


balance += amount;
System.out.println("Deposited: " + amount);
}

public void withdraw(double amount) {


if (amount <= balance) {

59/62
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Insufficient funds.");
}
}

public void checkBalance() {


System.out.println("Current balance: " + balance);
}

public static void main(String[] args) {


BankAccount account = new BankAccount();
Scanner scanner = new Scanner(System.in);
int option;

do {
System.out.println("1. Deposit 2. Withdraw 3. Check Balance 4. Exit");
option = scanner.nextInt();

switch (option) {
case 1:
System.out.print("Enter amount to deposit: ");
double depositAmount = scanner.nextDouble();
account.deposit(depositAmount);
break;
case 2:
System.out.print("Enter amount to withdraw: ");
double withdrawAmount = scanner.nextDouble();
account.withdraw(withdrawAmount);
break;
case 3:
account.checkBalance();
break;
case 4:
System.out.println("Exiting.");
break;
default:
System.out.println("Invalid option.");
}
} while (option != 4);

60/62
}
}

70. Simple Note-Taking Application

java

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

public class NoteTakingApp {


public static void main(String[] args) {
ArrayList<String> notes = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
String note;
int option;

do {
System.out.println("1. Add Note 2. View Notes 3. Exit");
option = scanner.nextInt();
scanner.nextLine(); // Consume newline

switch (option) {
case 1:
System.out.print("Enter note: ");
note = scanner.nextLine();
notes.add(note);
break;
case 2:
System.out.println("Notes:");
for (String n : notes) {
System.out.println(n);
}
break;
case 3:
System.out.println("Exiting.");
break;
default:
System.out.println("Invalid option.");
}
} while (option != 3);

61/62
}
}

These additional programs cover a variety of functionalities and concepts in Java, from basic
data handling to simple applications. Let me know if you need any more programs or specific
topics!

62/62

You might also like