num1 = 10
num2 = 5
sum = num1 + num2
print("Sum:", sum)
secret_number = 42
guess = input("Guess a number: ")
if int(guess) == secret_number:
print("You win!")
else:
print("Try again!")
word = "hangman"
guesses = []
for i in range(len(word)):
guesses.append("_")
print(" ".join(guesses))
while True:
guess = input("Guess a letter: ")
if guess in word:
print("Correct!")
for i in range(len(word)):
if word[i] == guess:
guesses[i] = guess
print(" ".join(guesses))
else:
print("Try again!")
word = "hangman"
guesses = []
for i in range(len(word)):
guesses.append("_")
print(" ".join(guesses))
while True:
guess = input("Guess a letter: ")
if guess in word:
print("Correct!")
for i in range(len(word)):
if word[i] == guess:
guesses[i] = guess
print(" ".join(guesses))
else:
print("Try again!")
score = 0
questions = ["What is the capital of France?", "Who wrote Romeo and Juliet?", "What is the largest planet in our solar system?"]
answers = ["Paris", "Shakespeare", "Jupiter"]
for i in range(len(questions)):
user_answer = input(questions[i] + " ")
if user_answer == answers[i]:
score += 1
print("Correct!")
else:
print("Sorry, that's incorrect.")
print("Your final score is:", score)
A simple game where the user has to guess a randomly generated number within a certain range
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 numberOfTries = 0;
int guess;
boolean win = false;
while (!win) {
System.out.print("Enter your guess (1-100): ");
guess = scanner.nextInt();
numberOfTries++;
if (guess == numberToGuess) {
win = true;
System.out.println("Congratulations! You've guessed the number in " + numberOfTries + " tries.");
} else if (guess < numberToGuess) {
System.out.println("Too low! Try again.");
} else {
System.out.println("Too high! Try again.");
}
}
}
}
A program to check if a number is prime.
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;
if (number <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
}
}
Create a system to manage employee details using classes and objects.
class Employee {
private String name;
private int id;
private double salary;
public Employee(String name, int id, double salary) {
this.name = name;
this.id = id;
this.salary = salary;
}
public void displayEmployeeDetails() {
System.out.println("Employee ID: " + id);
System.out.println("Employee Name: " + name);
System.out.println("Employee Salary: " + salary);
}
}
public class EmployeeManagementSystem {
public static void main(String[] args) {
Employee emp1 = new Employee("John Doe", 1, 50000);
Employee emp2 = new Employee("Jane Smith", 2, 60000);
emp1.displayEmployeeDetails();
System.out.println();
emp2.displayEmployeeDetails();
}
}
Create a simple banking system with classes for BankAccount and Customer.
class BankAccount {
private int accountNumber;
private double balance;
public BankAccount(int 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) {
balance -= amount;
System.out.println("Withdrew: " + amount);
} else {
System.out.println("Insufficient balance!");
}
}
public void displayBalance() {
System.out.println("Account Number: " + accountNumber);
System.out.println("Balance: " + balance);
}
}
class Customer {
private String name;
private BankAccount account;
public Customer(String name, BankAccount account) {
this.name = name;
this.account = account;
}
public void displayCustomerDetails() {
System.out.println("Customer Name: " + name);
account.displayBalance();
}
}
public class BankingSystem {
public static void main(String[] args) {
BankAccount account1 = new BankAccount(12345, 1000.0);
Customer customer1 = new Customer("Alice", account1);
customer1.displayCustomerDetails();
System.out.println();
account1.deposit(500.0);
account1.withdraw(300.0);
System.out.println();
customer1.displayCustomerDetails();
}
}
A program to perform division and handle exceptions.
import java.util.Scanner;
public class DivisionWithExceptionHandling {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the numerator: ");
int numerator = scanner.nextInt();
System.out.print("Enter the denominator: ");
int denominator = scanner.nextInt();
try {
int result = numerator / denominator;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
}
}
A program to handle divide by zero exception.
import java.util.Scanner;
public class DivideByZero {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the numerator: ");
int numerator = scanner.nextInt();
System.out.print("Enter the denominator: ");
int denominator = scanner.nextInt();
try {
int result = numerator / denominator;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
}
}
A program to handle exceptions when opening a file.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileOpen {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the file name: ");
String fileName = scanner.nextLine();
try {
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
System.out.println("File opened successfully.");
fileScanner.close();
} catch (FileNotFoundException e) {
System.out.println("Error: Failed to open the file.");
}
}
}
A program to handle array index out of bounds exception.
import java.util.Scanner;
public class ArrayIndexOutOfBounds {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the index to access the array: ");
int index = scanner.nextInt();
try {
System.out.println("Value at index " + index + ": " + numbers[index]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Index out of bounds.");
}
}
}
A program to manage a list of students using an ArrayList.
import java.util.ArrayList;
class Student {
private String name;
private int rollNumber;
public Student(String name, int rollNumber) {
this.name = name;
this.rollNumber = rollNumber;
}
public void displayStudentDetails() {
System.out.println("Roll Number: " + rollNumber);
System.out.println("Name: " + name);
}
}
public class StudentList {
public static void main(String[] args) {
ArrayList students = new ArrayList<>();
students.add(new Student("John Doe", 1));
students.add(new Student("Jane Smith", 2));
for (Student student : students) {
student.displayStudentDetails();
System.out.println();
}
}
}
A program to create a simple dictionary using a HashMap.
import java.util.HashMap;
import java.util.Scanner;
public class SimpleDictionary {
public static void main(String[] args) {
HashMap dictionary = new HashMap<>();
dictionary.put("hello", "a greeting");
dictionary.put("java", "a programming language");
dictionary.put("world", "the earth, together with all of its countries and peoples");
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = scanner.nextLine();
if (dictionary.containsKey(word)) {
System.out.println("Meaning: " + dictionary.get(word));
} else {
System.out.println("Word not found in dictionary.");
}
}
}
A program to perform operations on a list of integers.
import java.util.ArrayList;
import java.util.List;
public class ListOperations {
public static void main(String[] args) {
List numbers = new ArrayList<>();
// Add elements
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
// Remove an element
numbers.remove(Integer.valueOf(3));
// Display elements
System.out.println("List elements:");
for (int number : numbers) {
System.out.println(number);
}
}
}
A program to perform operations on a set of integers.
import java.util.HashSet;
import java.util.Set;
public class SetOperations {
public static void main(String[] args) {
Set numbers = new HashSet<>();
// Add elements
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
// Remove an element
numbers.remove(3);
// Display elements
System.out.println("Set elements:");
for (int number : numbers) {
System.out.println(number);
}
}
}
A program to perform operations on a map of integers and strings.
import java.util.HashMap;
import java.util.Map;
public class MapOperations {
public static void main(String[] args) {
Map students = new HashMap<>();
// Add elements
students.put(1, "Alice");
students.put(2, "Bob");
students.put(3, "Charlie");
// Remove an element
students.remove(2);
// Display elements
System.out.println("Map elements:");
for (Map.Entry entry : students.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
A program to write data to a file.
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFile {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("output.txt");
writer.write("Hello, this is a test file.");
writer.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
A program to read data from a file.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFromFile {
public static void main(String[] args) {
try {
File file = new File("output.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String data = scanner.nextLine();
System.out.println(data);
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}