0% found this document useful (0 votes)
132 views84 pages

Merged Solutions

Uploaded by

DEEPAK PAWAR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
132 views84 pages

Merged Solutions

Uploaded by

DEEPAK PAWAR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 84

PYTHON SOLUTIONS

slip1a: Write a Python program to accept n numbers in list and remove duplicates from a list.

CODE:

n = int(input("Enter the number of elements: "))

numbers = [int(input("Enter a number: ")) for _ in range(n)]

unique_numbers = list(set(numbers))

print("List after removing duplicates:", unique_numbers)

OUTPUT:
slip1b: Write Python GUI program to take accept your birthdate and output your age when a button is
pressed.

CODE:

import tkinter as tk

from tkinter import messagebox

from datetime import datetime

def calculate_age():

try:

birthdate = entry.get()

birth_date = datetime.strptime(birthdate, "%Y-%m-%d")

today = datetime.today()

age = today.year - birth_date.year - ((today.month, today.day) < (birth_date.month, birth_date.day))

messagebox.showinfo("Age", f"Your age is: {age} years")

except ValueError:

messagebox.showerror("Invalid input", "Please enter the date in YYYY-MM-DD format.")

window = tk.Tk()

window.title("Age Calculator")

label = tk.Label(window, text="Enter your birthdate (YYYY-MM-DD):")

label.pack(pady=10)

entry = tk.Entry(window)

entry.pack(pady=5)

button = tk.Button(window, text="Calculate Age", command=calculate_age)

button.pack(pady=10)

window.mainloop()
OUTPUT:
slip2a & slip24a & slip25a: Write a Python function that accepts a string and calculate the number of upper
case letters and lower case letters.

Sample String: 'The quick Brown Fox'

Expected Output:

No. of Upper case characters: 3

No. of Lower case characters: 13

CODE:

def count_case_letters(s):

upper_count = 0

lower_count = 0

for char in s:

if char.isupper():

upper_count += 1

elif char.islower():

lower_count += 1

print("No. of Upper case characters:", upper_count)

print("No. of Lower case characters:", lower_count)

sample_string = 'The quick Brown Fox'

count_case_letters(sample_string)

OUTPUT:
slip2b: Write Python GUI program to create a digital clock with Tkinter to display the time.

CODE:

import tkinter as tk

import time

def update_time():

current_time = time.strftime("%H:%M:%S")

clock_label.config(text=current_time)

clock_label.after(1000, update_time)

root = tk.Tk()

root.title("Digital Clock")

clock_label = tk.Label(root, font=("Helvetica", 48), bg="black", fg="white")

clock_label.pack(padx=20, pady=20)

update_time()

root.mainloop()

OUTPUT:
slip3a: Write a Python program to check if a given key already exists in a dictionary. If key exists
replace with another key/value pair.

CODE:

my_dict = {'a': 1, 'b': 2, 'c': 3}

old_key = 'b'

new_key = 'd'

new_value = 4

if old_key in my_dict:

del my_dict[old_key]

my_dict[new_key] = new_value

else:

my_dict[new_key] = new_value

print("Updated dictionary:", my_dict)

OUTPUT:
slip3b & slip10b: Write a python script to define a class student having members roll no, name, age,
gender. Create a subclass called Test with member marks of 3 subjects. Create three objects of the Test
class and display all the details of the student with total marks.

CODE:

class Student:

def init (self, roll_no, name, age, gender):

self.roll_no = roll_no

self.name = name

self.age = age

self.gender = gender

class Test(Student):

def init (self, roll_no, name, age, gender, marks):

super(). init (roll_no, name, age, gender)

self.marks = marks # Marks is a list of three subjects

def total_marks(self):

return sum(self.marks)

student1 = Test(1, "Alice", 20, "Female", [85, 90, 78])

student2 = Test(2, "Bob", 21, "Male", [75, 80, 82])

student3 = Test(3, "Charlie", 22, "Male", [90, 95, 88])

students = [student1, student2, student3]

for student in students:

print(f"Roll No: {student.roll_no}, Name: {student.name}, Age: {student.age}, Gender: {student.gender},


Total Marks: {student.total_marks()}")

OUTPUT:
slip4a: Write Python GUI program to create background with changing colors.

CODE:

import tkinter as tk

import random

def change_bg_color():

colors = ['red', 'green', 'blue', 'yellow', 'purple', 'orange']

chosen_color = random.choice(colors)

root.config(bg=chosen_color)

root.after(1000, change_bg_color)

root = tk.Tk()

root.title("Changing Background Color")

change_bg_color()

root.mainloop()

OUTPUT:
slip4b: Define a class Employee having members id, name, department, salary. Create a subclass called
manager with member bonus. Define methods accept and display in both the classes. Create n objects of the
manager class and display the details of the manager having the maximum total salary (salary+bonus).

CODE:

class Employee:

def init (self, id, name, department, salary):

self.id = id

self.name = name

self.department = department

self.salary = salary

def display(self):

print(f"ID: {self.id}, Name: {self.name}, Department: {self.department}, Salary: {self.salary}")

class Manager(Employee):

def init (self, id, name, department, salary, bonus):

super(). init (id, name, department, salary)

self.bonus = bonus

def display(self):

super().display()

print(f"Bonus: {self.bonus}")

def total_salary(self):

return self.salary + self.bonus

n = int(input("Enter number of managers: "))

managers = []

for _ in range(n):

print(f"\nEntering details for manager {_ + 1}:")

id = input("Enter manager ID: ")

name = input("Enter manager name: ")

department = input("Enter department: ")

salary = float(input("Enter salary: "))

bonus = float(input("Enter bonus: "))


manager = Manager(id, name, department, salary, bonus)

managers.append(manager)

max_manager = managers[0]

for manager in managers[1:]:

if manager.total_salary() > max_manager.total_salary():

max_manager = manager

print("\nManager with the maximum total salary:")

max_manager.display()

OUTPUT:
slip5a: Write a Python script using class, which has two methods get_String and print_String. get_String
accept a string from the user and print_String print the string in upper case.

CODE:

class SimpleString:

def init (self):

self.text = ""

def get_string(self):

self.text = input("Enter a string: ")

def print_string(self):

print(self.text.upper())

string_obj = SimpleString()

string_obj.get_string()

string_obj.print_string()

OUTPUT:
slip5b: Write a python script to generate Fibonacci terms using generator function.

CODE:

def fibonacci_generator(n):

a, b = 0, 1

for _ in range(n):

yield a

a, b = b, a + b

n = int(input("Enter the number of Fibonacci terms to generate: "))

for term in fibonacci_generator(n):

print(term)

OUTPUT:
slip6a: Write python script using package to calculate area and volume of cube and sphere.

CODE:

import math

class Geometry:

@staticmethod

def cube_area(side):

return 6 * (side ** 2)

@staticmethod

def cube_volume(side):

return side ** 3

@staticmethod

def sphere_area(radius):

return 4 * math.pi * (radius ** 2)

@staticmethod

def sphere_volume(radius):

return (4/3) * math.pi * (radius ** 3)

cube_side = 3

sphere_radius = 4

print(f"Cube Area: {Geometry.cube_area(cube_side)}")

print(f"Cube Volume: {Geometry.cube_volume(cube_side)}")

print(f"Sphere Area: {Geometry.sphere_area(sphere_radius)}")

print(f"Sphere Volume: {Geometry.sphere_volume(sphere_radius)}")

OUTPUT:
slip6b: Write a Python GUI program to create a label and change the label font style (font name, bold, size).
Specify separate check button for each style.

CODE:

import tkinter as tk

from tkinter import

font def update_font():

# Retrieve the selected options

selected_font_name = "Arial" if var_font.get() else "Helvetica"

font_size = 16 if var_size.get() else 12

font_weight = "bold" if var_bold.get() else "normal"

label.config(font=(selected_font_name, font_size, font_weight))

root = tk.Tk()

root.title("Change Label Font Style")

var_font = tk.BooleanVar()

var_bold = tk.BooleanVar()

var_size = tk.BooleanVar()

label = tk.Label(root, text="Hello, world!", font=("Helvetica", 12))

label.pack(pady=20)

check_font = tk.Checkbutton(root, text="Arial", variable=var_font, command=update_font)

check_font.pack()

check_bold = tk.Checkbutton(root, text="Bold", variable=var_bold, command=update_font)

check_bold.pack()

check_size = tk.Checkbutton(root, text="Large Size", variable=var_size, command=update_font)

check_size.pack()

root.mainloop()
OUTPUT:
slip7a: Write Python class to perform addition of two complex numbers using binary + operator overloading.

CODE:

class ComplexNumber:

def init (self, real, imaginary):

self.real = real

self.imaginary = imaginary

def add (self, other):

return ComplexNumber(self.real + other.real, self.imaginary +

other.imaginary) def str (self):

return f"{self.real} +

{self.imaginary}i" c1 = ComplexNumber(3,

2)

c2 = ComplexNumber(1, 7)

result = c1 + c2

print(f"c1 = {c1}\nc2 = {c2}")

print("Sum:", result)

OUTPUT:
slip7b: Write python GUI program to generate a random password with upper and lower case letters.

CODE:

import tkinter as tk

import random

import string

def generate_password(length):

characters = string.ascii_letters # Upper and lower case letters

password = ''.join(random.choice(characters) for _ in range(length))

password_entry.delete(0, tk.END) # Clear previous password

password_entry.insert(0, password) # Insert the new password

root = tk.Tk()

root.title("Random Password Generator")

length_label = tk.Label(root, text="Password Length:")

length_label.pack(pady=10)

length_entry = tk.Entry(root)

length_entry.pack(pady=5)

generate_button = tk.Button(root, text="Generate Password", command=lambda:


generate_password(int(length_entry.get())))

generate_button.pack(pady=20)

password_entry = tk.Entry(root, width=30)

password_entry.pack(pady=5)

root.mainloop()

OUTPUT:
slip8a & slip10a: Write a python script to find the repeated items of a tuple.

CODE:

my_tuple = (1, 2, 3, 4, 2, 5, 6, 1, 7, 8, 3)

item_counts = {}

for item in my_tuple:

if item in item_counts:

item_counts[item] += 1

else:

item_counts[item] = 1

repeated_items = [item for item, count in item_counts.items() if count > 1]

print("Repeated items:", repeated_items)

OUTPUT:
slip8b & slip9b: Write a Python class which has two methods get_String and print_String. get_String
accept a string from the user and print_String print the string in upper case. Further modify the program to
reverse a string word by word and print it in lower case.

CODE:

class SimpleString:

def init (self):

self.text = ""

def get_string(self):

self.text = input("Enter a string: ")

def print_string(self):

print("Uppercase:", self.text.upper())

def reverse_and_lower(self):

reversed_words = ' '.join(self.text.split()[::-1])

print("Reversed and Lowercase:", reversed_words.lower())

string_obj = SimpleString()

string_obj.get_string()

string_obj.print_string()

string_obj.reverse_and_lower()

OUTPUT:
slip9a: Write a Python script using class to reverse a string word by word.

CODE:

class StringReverser:

def init (self, text=""):

self.text = text

def set_text(self):

self.text = input("Enter a string: ")

def reverse_words(self):

reversed_words = ' '.join(self.text.split()[::-1])

print("Reversed:", reversed_words)

reverser = StringReverser()

reverser.set_text()

reverser.reverse_words()

OUTPUT:
slip11a & slip21a: Define a class named Rectangle which can be constructed by a length and width. The
Rectangle class has a method which can compute the area and Perimeter.

CODE:

class Rectangle:

def init (self, length, width):

self.length = length

self.width = width

def area(self):

"""Calculate the area of the rectangle."""

return self.length * self.width

def perimeter(self):

"""Calculate the perimeter of the rectangle."""

return 2 * (self.length + self.width)

if name == " main ":

length = float(input("Enter the length of the rectangle: "))

width = float(input("Enter the width of the rectangle: "))

rectangle = Rectangle(length, width)

print(f"Area of the rectangle: {rectangle.area()}")

print(f"Perimeter of the rectangle: {rectangle.perimeter()}")

OUTPUT:
Slip11b & slip 25b: Write a Python script to Create a Class which Performs Basic Calculator Operations.

CODE:

class Calculator:

def add(self, a, b):

return a + b

def subtract(self, a, b):

return a - b

def multiply(self, a, b):

return a * b

def divide(self, a, b):

if b == 0:

return "Error: Division by zero"

return a / b

calc = Calculator()

a = 10

b=5

print("Addition:", calc.add(a, b))

print("Subtraction:", calc.subtract(a, b))

print("Multiplication:", calc.multiply(a, b))

print("Division:", calc.divide(a, b))

print("Division by zero:", calc.divide(a, 0))

OUTPUT:
slip12a: Write a Python GUI program to create a label and change the label font style (font name, bold, size)
using tkinter module.

CODE:

import tkinter as tk

from tkinter import

font

def change_font(name, size, bold):

new_font = (name, size, 'bold' if bold else 'normal')

label.config(font=new_font)

root = tk.Tk()

root.title("Font Style Changer")

label = tk.Label(root, text="Change my font!", font=("Arial", 12))

label.pack(pady=20)

menu = tk.Menu(root)

font_menu = tk.Menu(menu, tearoff=0)

font_options = [

("Arial", 12, False),

("Arial", 16, True),

("Helvetica", 14, False),

("Courier", 18, True)

for name, size, bold in font_options:

font_menu.add_command(label=f"{name} {size} {'Bold' if bold else 'Regular'}",

command=lambda n=name, s=size, b=bold: change_font(n, s, b))

menu.add_cascade(label="Fonts", menu=font_menu)

root.config(menu=menu)

root.mainloop()
OUTPUT:
slip12b & slip19b & slip29b: Write a python program to count repeated

characters in a string. Sample string: 'thequickbrownfoxjumpsoverthelazydog'

Expected output: o-4, e-3, u-2, h-2, r-2, t-2

CODE:

sample_string = 'thequickbrownfoxjumpsoverthelazydog'

char_count = {}

for char in sample_string:

if char in char_count:

char_count[char] += 1

else:

char_count[char] = 1

for char, count in char_count.items():

if count > 1:

print(f"{char}-{count}", end=", ")

OUTPUT:
slip13a & slip14a: Write a Python program to input a positive integer. Display correct message for
correct and incorrect input. (Use Exception Handling)

CODE:

def get_positive_integer():

try:

num = int(input("Enter a positive integer:

")) if num <= 0:

raise ValueError("The number must be positive.")

print(f"You entered a valid positive integer: {num}")

except ValueError as e:

print(f"Invalid input: {e}")

get_positive_integer()

OUTPUT:
slip 13b: Write a program to implement the concept of queue using list.

CODE:

queue = []

def enqueue(item):

queue.append(item)

def dequeue():

if not is_empty():

return queue.pop(0)

else:

raise IndexError("Dequeue from an empty queue")

def is_empty():

return len(queue) == 0

enqueue(1)

enqueue(2)

enqueue(3)

print("Dequeue:", dequeue()) # Output: Dequeue: 1

print("Is empty?", is_empty()) # Output: Is empty? False

OUTPUT:
Slip14b & slip20b: Write a Python script to generate and print a dictionary which contains a number
(between 1 and n) in the form(x,x*x).

Sample Dictionary (n=5) Expected Output: {1:1, 2:4, 3:9, 4:16, 5:25}

CODE:

def generate_square_dict(n):

return {x: x * x for x in range(1, n + 1)}

n=5

result_dict = generate_square_dict(n)

print(result_dict)

OUTPUT:
slip15a: Write a Python class named Student with two attributes student_name, marks. Modify the attribute
values of the said class and print the original and modified values of the said attributes.

CODE:

class Student:

def init (self, student_name, marks):

self.student_name = student_name

self.marks = marks

def modify_attributes(self, new_name, new_marks):

self.student_name = new_name

self.marks = new_marks

def print_attributes(self):

print(f"Student Name: {self.student_name}")

print(f"Marks: {self.marks}")

student = Student("Alice", 85)

print("Original values:")

student.print_attributes()

student.modify_attributes("Bob", 90)

print("\nModified values:")

student.print_attributes()

OUTPUT:
slip15b: Write a python program to accept string and remove the characters which have odd index values of
given string using user defined function.

CODE:

def remove_odd_index_chars(s):

return s[::2]

user_input = input("Enter a string: ")

result = remove_odd_index_chars(user_input)

print("String after removing characters at odd indices:", result)

OUTPUT:
slip16a & slip 18a: Create a list a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] and write a python program that prints
out all the elements of the list that are less than 5

CODE:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

for number in a:

if number < 5:

print(number)

OUTPUT:
Slip 16b & slip21b: Write a Python program to convert a tuple of string values to a tuple of

integer values. Original tuple values: (('333', '33'), ('1416', '55'))

New tuple values: ((333, 33), (1416, 55))

CODE:

original_tuple = (('333', '33'), ('1416', '55'))

new_tuple = tuple((int(x), int(y)) for x, y in original_tuple)

print("Original tuple values:", original_tuple)

print("New tuple values:", new_tuple)

OUTPUT:
slip17a & slip 20a & slip29a: Write a python program to create a class Circle and Compute the Area and
the circumferences of the circle.(use parameterized constructor)

CODE:

import math

class Circle:

def init (self, radius):

self.radius = radius

def area(self):

return math.pi * self.radius * self.radius

def circumference(self):

return 2 * math.pi * self.radius

circle = Circle(radius=5)

print("Area:", circle.area()) # Output: Area: 78.53981633974483

print("Circumference:", circle.circumference()) # Output: Circumference: 31.41592653589794

OUTPUT:
slip17b & slip18b: Write a python script to define the class person having members name, address. Create a
subclass called Employee with members staffed salary. Create 'n' objects of the Employee class and display
all the details of the employee.

CODE:

class Person:

def init (self, name, address):

self.name = name

self.address = address

def display_info(self):

print(f"Name: {self.name}")

print(f"Address: {self.address}")

class Employee(Person):

def init (self, name, address, staff_id, salary):

super(). init (name, address)

self.staff_id = staff_id

self.salary = salary

def display_info(self):

super().display_info()

print(f"Staff ID: {self.staff_id}")

print(f"Salary: $

{self.salary:.2f}")

def main():

n = int(input("Enter the number of employees: "))

employees = []

for _ in range(n):

name = input("\nEnter name: ")

address = input("Enter address: ")

staff_id = input("Enter staff ID: ")

salary = float(input("Enter salary: "))

employee = Employee(name, address, staff_id, salary)

employees.append(employee)
print("\nEmployee Details:")

for emp in employees:

emp.display_info()

print("-" * 30)

if name == " main ":

main()

OUTPUT:

slip19a & slip28a: Write a Python GUI program to create a list of Computer Science Courses using
Tkinter module (use Listbox).

CODE:

import tkinter as tk

def display_selected_course(event):

selected_course = course_listbox.get(course_listbox.curselection())

selection_label.config(text=f"Selected Course: {selected_course}")

root = tk.Tk()

root.title("Computer Science Courses")

courses = [

"Introduction to

Programming", "Data

Structures", "Algorithms",

"Database Management

Systems", "Computer Networks",

"Operating Systems",

"Software Engineering",

"Web Development",

"Machine Learning",

"Artificial Intelligence"

course_listbox = tk.Listbox(root, width=50, height=10)

course_listbox.pack(pady=20)

for course in courses:

course_listbox.insert(tk.END, course)

selection_label = tk.Label(root, text="Selected Course: None", font=("Arial", 12))

selection_label.pack(pady=10)

course_listbox.bind('<<ListboxSelect>>', display_selected_course)

root.mainloop()
OUTPUT:

slip22a: Write a python class to accept a string and number n from user and display n repetition of strings by
overloading * operator.

CODE:

class Repeater:

def init (self, string):

self.string = string

def mul (self, n):

if isinstance(n, int) and n >= 0:

return self.string * n

else:

raise ValueError("The multiplier must be a non-negative integer.")

def main():

user_string = input("Enter a string: ")

n = int(input("Enter the number of repetitions (n): "))

repeater = Repeater(user_string)

try:

result = repeater * n # Overloading the * operator

print(f"Result: {result}")

except ValueError as e:

print(e)

if name == " main ":

main()

OUTPUT:
slip22b & slip26b: Write a python script to implement bubble sort using list

CODE:

def bubble_sort(arr):

n = len(arr)

for i in range(n):

for j in range(0, n-i-1):

if arr[j] > arr[j + 1]:

arr[j], arr[j + 1] = arr[j + 1], arr[j]

def main():

# Input list from the user

user_input = input("Enter numbers separated by spaces: ")

arr = list(map(int, user_input.split()))

print("Original list:", arr)

bubble_sort(arr)

print("Sorted list:", arr)

if name == " main ":

main()

OUTPUT:
slip23a: Write a Python GUI program to create a label and change the label font style (font name, bold, size)
using tkinter module.

CODE:

import tkinter as tk

from tkinter import

font

def change_font(name, size, bold):

new_font = (name, size, 'bold' if bold else 'normal')

label.config(font=new_font)

root = tk.Tk()

root.title("Font Style Changer")

label = tk.Label(root, text="Change my font!", font=("Arial", 12))

label.pack(pady=20)

menu = tk.Menu(root)

font_menu = tk.Menu(menu, tearoff=0)

font_options = [

("Arial", 12, False),

("Arial", 16, True),

("Helvetica", 14, False),

("Courier", 18, True)

for name, size, bold in font_options:

font_menu.add_command(label=f"{name} {size} {'Bold' if bold else 'Regular'}",

command=lambda n=name, s=size, b=bold: change_font(n, s, b))

menu.add_cascade(label="Fonts", menu=font_menu)

root.config(menu=menu)

root.mainloop()
OUTPUT:
slip23b & slip24b: Create a class circles having members radius. Use operator overloading to add the
radius of two circle objects. Also display the area of circle.

CODE:

import math

class Circle:

def init (self, radius):

self.radius = radius

def add (self, other):

"""Overload the + operator to add the radii of two circles."""

return Circle(self.radius + other.radius)

def area(self):

"""Calculate the area of the circle."""

return math.pi * (self.radius ** 2)

def str (self):

"""String representation of the circle."""

return f"Circle(radius={self.radius:.2f},

area={self.area():.2f})" def main():

radius1 = float(input("Enter the radius of the first circle: "))

radius2 = float(input("Enter the radius of the second circle: "))

circle1 = Circle(radius1)

circle2 = Circle(radius2)

circle3 = circle1 + circle2 # This uses the overloaded + operator

print(circle1)

print(circle2)

print(circle3)

if name == " main ":

main()

OUTPUT:
slip26a: Write an anonymous function to find area of square and rectangle.

CODE:

area_square = lambda side: side * side

area_rectangle = lambda length, width: length * width

side = 4

length = 5

width = 3

print("Area of square with side", side, "is:", area_square(side))

print("Area of rectangle with length", length, "and width", width, "is:", area_rectangle(length, width))

OUTPUT:
slip27a: Write a Python program to unzip a list of tuples into individual lists.

CODE:

list_of_tuples = [(1, 'a'), (2, 'b'), (3, 'c')]

list1, list2 = zip(*list_of_tuples)

list1 = list(list1)

list2 = list(list2)

print("List 1:", list1)

print("List 2:", list2)

OUTPUT:
Slip27b & 28b: Write a Python program to accept two lists and merge the two lists into list of tuple.

CODE:

def merge_lists_into_tuples(list1, list2):

return list(zip(list1, list2))

def main():

list1 = input("Enter the first list of items (comma-separated): ").split(',')

list2 = input("Enter the second list of items (comma-separated): ").split(',')

list1 = [item.strip() for item in list1]

list2 = [item.strip() for item in list2]

merged_list = merge_lists_into_tuples(list1, list2)

print("Merged list of tuples:", merged_list)

if name == " main ":

main()

OUTPUT:
slip30a: Write a Python GUI program to accept a string and a character from user and count the occurrences
of a character in a string.

CODE:

import tkinter as tk

from tkinter import messagebox

def count_character():

input_string = entry_string.get()

input_char = entry_char.get()

if len(input_char) != 1:

messagebox.showerror("Error", "Please enter exactly one character.")

return

count = input_string.count(input_char)

messagebox.showinfo("Result", f"The character '{input_char}' occurs {count} times in the string.")

root = tk.Tk()

root.title("Character Counter")

label_string = tk.Label(root, text="Enter a string:")

label_string.pack(pady=5)

entry_string = tk.Entry(root, width=50)

entry_string.pack(pady=5)

label_char = tk.Label(root, text="Enter a character:")

label_char.pack(pady=5)

entry_char = tk.Entry(root, width=5)

entry_char.pack(pady=5)

count_button = tk.Button(root, text="Count Occurrences", command=count_character)

count_button.pack(pady=20)

root.mainloop()
OUTPUT:
slip30b: Python Program to Create a Class in which One Method Accepts a String from the User and
Another method Prints it. Define a class named Country which has a method called print Nationality. Define
subclass named state from Country which has a mehtod called printState. Write a method to print state,
country and nationality.

CODE:

class Country:

def init (self):

self.nationality = ""

def input_nationality(self):

self.nationality = input("Enter your nationality: ")

def print_nationality(self):

print(f"Nationality: {self.nationality}")

class State(Country):

def init (self):

super(). init ()

self.state = ""

def input_state(self):

self.state = input("Enter your state: ")

def print_state(self):

print(f"State: {self.state}")

print(f"Country: {self.nationality}")

print(f"Nationality: {self.nationality}")

my_location = State()

my_location.input_nationality()

my_location.input_state()

my_location.print_state()

OUTPUT:
JAVA PRACTICAL SOLN

slip1a & 7a & slip14a: Write a ‘java’ program to display characters from ‘A’ to ‘Z’.
CODE:
public class Slip1A{
public static void main(String[] args){
for(char i='A';i<='Z';i++){
System.out.println(i);
}
}
}
slip1b & slip10b & slip15b: Write a ‘java’ program to copy only non-numeric data from one file to another
file.
CODE:
import java.io.*;
//import java.io.BufferedReader;
//import java.io.FileReader;
//import java.io.IOException;

public class Slip1b{


public static void main(String[] args){
FileInputStream instream = null;
FileOutputStream outstream = null;

try{
File infile = new File("C:\\Users\\DELL\\Documents\\java\\old.txt");
File outfile = new File("C:\\Users\\DELL\\Documents\\java\\output.txt");

instream = new FileInputStream(infile);


outstream = new FileOutputStream(outfile);

InputStreamReader isReader = new InputStreamReader(instream);


BufferedReader reader = new BufferedReader(isReader);
StringBuffer sb = new StringBuffer();

String str;
byte[] buffer = new byte[1024];
int length;

while((str = reader.readLine()) != null){


sb.append(str);
}

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


char c = sb.charAt(i);
if(Character.isDigit(c)){
String newfile = String.valueOf(c);
byte[] out = newfile.getBytes();
System.out.print(newfile);
outstream.write(out);
}
}
System.out.print('\n');
}
catch(IOException e){
e.printStackTrace();
}

}
}
slip2a & slip10a: Write a java program to display all the vowels from a given string.
CODE:
public class Slip2A {
public static void main(String[] args) {
String str = "hello world";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
System.out.println("Vowels in string: "+ch);
}
}
}
}
slip2b & slip19b & slip26a & slip29a: Write a Java program to display ASCII values of the characters from
a file.
CODE:
import java.util.*;
import java.io.*;

class Slip26a{
public static void main(String[] agrs) throws IOException{
char ch;
FileReader fr = new FileReader("old.txt");
int c;
while((c = fr.read()) != -1){
ch = (char)c;
if(Character.isDigit(ch) == false && (Character.isSpaceChar(c) == false)){
System.out.println("ASCII " +ch+ ":" +c);
}
}
fr.close();
}
}
slip3a: Write a ‘java’ program to check whether given number is Armstrong or not.
(Use static keyword)
CODE:
public class Slip3A{
public static void main(String[] args) {
int num = 153; // Specified number to check
int temp=num;
int rem,sum=0;
while(num>0){
rem=num%10;
num=num/10;
sum=sum+rem*rem*rem;
}
// Check if the number is an Armstrong number
if (temp==sum) {
System.out.println(" is an Armstrong number.");
} else {
System.out.println(" is not an Armstrong number.");
}
}
}
slip3b: Define an abstract class Shape with abstract methods area () and volume (). Derive
abstract class Shape into two classes Cone and Cylinder. Write a java Program
to calculate area and volume of Cone and Cylinder. (Use Super Keyword.)
CODE:
abstract class Shape {
// Abstract methods for calculating area and volume
abstract double area();
abstract double volume();
}

class Cone extends Shape {


private double radius;
private double height;

// Constructor for Cone


public Cone(double radius, double height) {
this.radius = radius;
this.height = height;
}

// Method to calculate the surface area of a cone


double area() {
double slantHeight = Math.sqrt((radius * radius) + (height * height));
return Math.PI * radius * (radius + slantHeight);
}

// Method to calculate the volume of a cone


double volume() {
return (1.0 / 3) * Math.PI * radius * radius * height;
}
}

class Cylinder extends Shape {


private double radius;
private double height;

// Constructor for Cylinder


public Cylinder(double radius, double height) {
this.radius = radius;
this.height = height;
}

// Method to calculate the surface area of a cylinder


double area() {
return 2 * Math.PI * radius * (radius + height);
}

// Method to calculate the volume of a cylinder


double volume() {
return Math.PI * radius * radius * height;
}
}

public class Main {


public static void main(String[] args) {
// Create a Cone object
Cone cone = new Cone(5, 10);
System.out.println("Cone Area: " + cone.area());
System.out.println("Cone Volume: " + cone.volume());

// Create a Cylinder object


Cylinder cylinder = new Cylinder(5, 10);
System.out.println("Cylinder Area: " + cylinder.area());
System.out.println("Cylinder Volume: " + cylinder.volume());
}
}
slip4a: Write a java program to display alternate character from a given string.
CODE:
import java.util.Scanner;

public class Slip4A{


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
scanner.close();
// Display alternate characters from the string
System.out.print("Alternate characters: ");
for (int i = 0; i < input.length(); i += 2) {
System.out.print(input.charAt(i) + " ");
}
}
}
slip4b & slip11b & slip12b & slip20b & slip27b: Construct a Linked List containing name: CPP, Java,
Python and PHP. Then
extend your java program to do the following:
i. Display the contents of the List using an Iterator
ii. Display the contents of the List in reverse order using a ListIterator.
CODE:
import java.util.*;

public class LinkedList{


public static void main(String[] args){
LinkedList<String> ll = new LinkedList<>();
ll.add("CPP");
ll.add("JAVA");
ll.add("Python");
ll.add("PHP");

System.out.println("display content using iterator: ");


Iterator<String> it = ll.iterator();
while(it.hasNext()){
System.out.println(it.next());
}

System.out.println("display content using list iterator: ");


ListIterator<String> lit = ll.listIterator();
while(lit.hasNext()){
lit.next();
}

while(lit.hasPrevious()){
System.out.println(" " +lit.previous());
}
}
}
slip5a: Write a java program to display following pattern:
5
45
345
2345
12345
CODE:
public class NumberPattern {
public static void main(String[] args) {
// Display numbers in the specified pattern
for (int i = 5; i >= 1; i--) {
for (int j = i; j <= 5; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
slip5b & slip24b: Write a java program to accept list of file names through command line. Delete the
files having extension .txt. Display name, location and size of remaining files.
CODE:
import java.io.*;

class Slip5b{
public static void main(String[] args){
for(int i=0; i<args.length; i++){
File file = new File(args[i]);
if(file.isFile()){
String name = file.getName();
if(name.endsWith(".txt")){
file.delete();
System.out.println("file is deleted successfully!" +file);
}
else{
System.out.println("file name: " +name + "\nfile location: " +file.getAbsolutePath() + "\nfile size: "
+file.length() +"bytes");
}
}
else{
System.out.println(args[i] + "is not a file");
}
}
}
}
slip6a: Write a java program to accept a number from user, if it zero then throw user
defined Exception “Number Is Zero”, otherwise calculate the sum of first and last digit
of that number. (Use static keyword).
CODE:
import java.util.Scanner;

// User-defined exception class


class NumberIsZeroException extends Exception {
public NumberIsZeroException(String message) {
super(message);
}
}

public class SumOfDigits {

// Static method to calculate the sum of the first and last digit
public static int sumOfFirstAndLastDigit(int number) {
int lastDigit = number % 10; // Get last digit
int firstDigit = Character.getNumericValue(Integer.toString(number).charAt(0)); // Get first digit
return firstDigit + lastDigit; // Return the sum
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Prompt user to enter a number


System.out.print("Enter a number: ");
int num = scanner.nextInt();

try {
// Check if the number is zero
if (num == 0) {
throw new NumberIsZeroException("Number Is Zero");
}
// Calculate and display the sum of the first and last digit
int sum = sumOfFirstAndLastDigit(num);
System.out.println("Sum of the first and last digit: " + sum);
} catch (NumberIsZeroException e) {
System.out.println(e.getMessage()); // Display the exception message
} finally {
// Close the scanner
scanner.close();
}
}
}
slip6b & Slip7b: Write a java program to display transpose of a given matrix.
CODE:
import java.util.Scanner;

public class TransposeMatrix {


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

// Accept the dimensions of the matrix


System.out.print("Enter the number of r: ");
int r = scanner.nextInt();
System.out.print("Enter the number of c: ");
int c = scanner.nextInt();

// Create the matrix


int[][] matrix = new int[r][c];

// Input elements into the matrix


System.out.println("Enter the elements of the matrix:");
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
matrix[i][j] = scanner.nextInt();
}
}

// Display the original matrix


System.out.println("Original Matrix:");
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}

// Calculate and display the transpose of the matrix


System.out.println("Transpose Matrix:");
for (int i = 0; i < c; i++) {
for (int j = 0; j < r; j++) {
System.out.print(matrix[j][i] + " "); // Print transpose
}
System.out.println();
}

// Close the scanner


scanner.close();
}
}
Slip8a: Define an Interface Shape with abstract method area(). Write a java program to
calculate an area of Circle and Sphere.(use final keyword)
CODE:
import java.util.Scanner;

interface Shape {
double area();
}

class Circle implements Shape {


private final double radius;

public Circle(double radius) {


this.radius = radius;
}

public double area() {


return Math.PI * radius * radius;
}
}

class Sphere implements Shape {


private final double radius;

public Sphere(double radius) {


this.radius = radius;
}

public double area() {


return 4 * Math.PI * radius * radius;
}
}

public class AreaCalculator {


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

System.out.print("Enter the radius of the Circle: ");


double circleRadius = scanner.nextDouble();
Shape circle = new Circle(circleRadius);
System.out.println("Area of Circle: " + circle.area());

System.out.print("Enter the radius of the Sphere: ");


double sphereRadius = scanner.nextDouble();
Shape sphere = new Sphere(sphereRadius);
System.out.println("Area of Sphere: " + sphere.area());

scanner.close();
}
}
Slip8b: Write a java program to display the files having extension .txt from a given
directory.
CODE:
import java.io.*;

class Slip8b{
public static void main(String[] args){
File file = new File("C:\\Users\\DELL\\Documents\\java");
File [] fl = file.listFiles((d, f)-> f.toLowerCase().endsWith(".txt"));

for(File f: fl){
System.out.println(f.getName());
}
}
}
Slip9a & slip16a: Write a java Program to display following pattern:
1
01
010
1010
CODE:
public class PatternDisplay {
public static void main(String[] args) {
int rows = 4; // Number of rows in the pattern

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


for (int j = 0; j <= i; j++) {
// Determine the value to print based on the position
if ((i + j) % 2 == 0) {
System.out.print("1 ");
} else {
System.out.print("0 ");
}
}
System.out.println(); // Move to the next line after each row
}
}
}
Slip9b & slip14b: Write a java program to validate PAN number and Mobile Number. If it is invalid
then throw user defined Exception “Invalid Data”, otherwise display it.
CODE:
import java.util.Scanner;

class InvalidDataException extends Exception {


public InvalidDataException(String message) {
super(message);
}
}

public class DataValidator {


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

// Input PAN number


System.out.print("Enter PAN number: ");
String pan = scanner.nextLine();

// Input Mobile number


System.out.print("Enter Mobile number: ");
String mobile = scanner.nextLine();

try {
validatePAN(pan);
validateMobile(mobile);
System.out.println("Valid PAN number: " + pan);
System.out.println("Valid Mobile number: " + mobile);
} catch (InvalidDataException e) {
System.out.println(e.getMessage());
} finally {
scanner.close();
}
}

public static void validatePAN(String pan) throws InvalidDataException {


if (!pan.matches("[A-Z]{5}[0-9]{4}[A-Z]")) {
throw new InvalidDataException("Invalid PAN number. It should be in the format: ABCDE1234F");
}
}

public static void validateMobile(String mobile) throws InvalidDataException {


if (!mobile.matches("\\d{10}")) {
throw new InvalidDataException("Invalid Mobile number. It should be a 10-digit number.");
}
}
}
slip12a & slip19a: Write a java program to display each String in reverse order from a String array.
CODE:
public class ReverseStringArray {
public static void main(String[] args) {
String[] strings = {"Hello", "World", "Java", "Programming"};

System.out.println("Strings in reverse order:");


for (String str : strings) {
System.out.println(reverseString(str));
}
}

public static String reverseString(String str) {


StringBuilder reversed = new StringBuilder(str);
return reversed.reverse().toString();
}
}
slip13a: Write a java program to accept ‘n’ integers from the user & store them in an
ArrayList collection. Display the elements of ArrayList collection in reverse order.
CODE:
import java.util.*;

class Slip13a{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("enter no. of elements: ");

int n = sc.nextInt();
ArrayList<String> list = new ArrayList<>();
System.out.println("enter the elements of array list collection: ");
for(int i = 0; i<n; i++){
String ele = sc.next();
list.add(ele);
}

System.out.println("original array list: " +list);


Collections.reverse(list);
System.out.println("reversed array list: " +list);

}
}
slip13b & slip17b & slip21b: Write a java program that asks the user name, and then greets the user by
name Before outputting the user's name, convert it to upper case letters. For example, if
the user's name is Raj, then the program should respond "Hello, RAJ, nice to meet
you!".
CODE:
import java.util.Scanner;

public class GreetUser {


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

System.out.print("Enter your name: ");


String name = scanner.nextLine();

String upperCaseName = name.toUpperCase(); // Convert name to uppercase

System.out.println("Hello, " + upperCaseName + ", nice to meet you!");

scanner.close();
}
}
slip15a & slip24a: Write a java program to search given name into the array, if it is found then display
its index otherwise display appropriate message.
CODE:
import java.util.Scanner;

public class SimpleNameSearch {


public static void main(String[] args) {
String[] names = {"Alice", "Bob", "Charlie", "David", "Eve"};
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the name to search: ");


String searchName = scanner.nextLine();

boolean found = false;


int index = -1;

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


if (names[i].equalsIgnoreCase(searchName)) {
found = true;
index = i;
break; // Exit the loop if the name is found
}
}

if (found) {
System.out.println("Name found at index: " + index);
} else {
System.out.println("Name not found in the array.");
}

scanner.close();
}
}
slip16b & slip18b & slip29b: Write a java program to copy the data from one file into another file, while
copying change the case of characters in target file and replaces all digits by ‘*’ symbol.
CODE:
import java.io.*;

class Slip18b{
public static void main(String[] args) throws IOException{
FileReader fr = new FileReader("old.txt");
FileWriter fw = new FileWriter("new.txt");

int c;

while((c = fr.read()) != -1){


if(Character.isDigit(c) == false){
if(Character.isUpperCase(c)){
fw.write(Character.toLowerCase(c));
}
else if(Character.isLowerCase(c)){
fw.write(Character.toUpperCase(c));
}
}
else{
fw.write("*");
}
}
fr.close();
fw.close();
}
}
slip17a & slip18a: Write a Java program to calculate area of Circle, Triangle & Rectangle. (Use Method
Overloading)
CODE:
import java.util.Scanner;

public class AreaCalculator {

public double areaCircle(double radius) {


return Math.PI * radius * radius;
}

public double areaTriangle(double base, double height) {


return 0.5 * base * height;
}

public double areaRectangle(double length, double width) {


return length * width;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
AreaCalculator calculator = new AreaCalculator();

System.out.print("Enter the radius of the Circle: ");


double circleRadius = scanner.nextDouble();
System.out.println("Area of Circle: " + calculator.areaCircle(circleRadius));

System.out.print("Enter the base of the Triangle: ");


double triangleBase = scanner.nextDouble();
System.out.print("Enter the height of the Triangle: ");
double triangleHeight = scanner.nextDouble();
System.out.println("Area of Triangle: " + calculator.areaTriangle(triangleBase, triangleHeight));

System.out.print("Enter the length of the Rectangle: ");


double rectangleLength = scanner.nextDouble();
System.out.print("Enter the width of the Rectangle: ");
double rectangleWidth = scanner.nextDouble();
System.out.println("Area of Rectangle: " + calculator.areaRectangle(rectangleLength, rectangleWidth));

scanner.close();
}
}
Slip20a: Write a java program using AWT to create a Frame with title “TYBBACA”,
background color RED. If user clicks on close button then frame should close.
CODE:
import java.awt.*;
import java.awt.event.*;

public class TYBBACAFrame extends Frame {


public TYBBACAFrame() {
setTitle("TYBBACA");
setBackground(Color.RED);
setSize(400, 300);

// Add a window listener to handle the close button action


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose(); // Close the frame
}
});

setVisible(true);
}

public static void main(String[] args) {


new TYBBACAFrame();
}
}
Slip21a: Write a java program to display each word from a file in reverse order.
CODE:
import java.io.*;
import java.util.*;

class Slip21a{
public static void main(String[] args) throws IOException{
FileReader fr = new FileReader("old.txt");
FileWriter fw = new FileWriter("new2.txt");

try{
Scanner sc = new Scanner(fr);

while(sc.hasNextLine()){
String s = sc.nextLine();
StringBuffer buffer = new StringBuffer(s);
buffer = buffer.reverse();
String res = buffer.toString();
fw.write(res);
}
}
catch(Exception e){}
fr.close();
fw.close();
}
}
Slip22a: Write a Java program to calculate factorial of a number using recursion.
CODE:
import java.util.Scanner;

public class SimpleFactorial {

public static long factorial(int n) {


if (n == 0 || n == 1) {
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();
long result = factorial(number);
System.out.println("Factorial of " + number + " is: " + result);
scanner.close();
}
}
Slip22b: Write a java program for the following: [25 M]
1. To create a file.
2. To rename a file.
3. To delete a file.
4. To display path of a file.
CODE:
import java.io.*;
import java.util.*;

class Slip22b{
public static void main(String[] args) throws IOException{
Scanner sc = new Scanner(System.in);

System.out.println("1. create a file \n2. rename a file \n3. delete a file \n4. display file path");
System.out.println("enter a file name: ");

String str = sc.nextLine();


File file = new File(str);

System.out.print("choose your option: ");


int ch = sc.nextInt();

switch(ch){
case 1:
if(file.createNewFile()){
System.out.println("file created: " +file.getName());
}
else{
System.out.println("file already exists");
}
break;
case 2:
System.out.print("enter new file name: ");
String nf = sc.nextLine();
File nf1 = new File(nf);

if(file.renameTo(nf1)){
System.out.println("file renamed");
}
else{
System.out.println("file can't be renamed");
}
break;
case 3:
if(file.delete()){
System.out.println("delete the file: " +file.getName());
}
else{
System.out.println("failed to delete the file");
}
break;
case 4:
System.out.println("file location: " +file.getAbsolutePath());
break;
default:
System.out.println("please choose the correct option");
break;
}
}
}
Slip23a: Write a java program to check whether given file is hidden or not. If not then
display its path, otherwise display appropriate message.
CODE:
slip23a:

import java.io.*;
import java.util.*;

public class Slip23a{


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

try{
System.out.print("enter file name: ");
String str = sc.nextLine();
File file = new File(str);

if(file.isHidden()){
System.out.println("file is hidden");
}
else{
System.out.println("file location: " +file.getAbsolutePath());
}
}
catch(Exception e){}
}
}
Slip25a: Write a java program to check whether given string is palindrome or not.
CODE:
import java.util.Scanner;

public class SimplePalindromeChecker {


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

// Check if the string is a palindrome


if (isPalindrome(input)) {
System.out.println(input + " is a palindrome.");
} else {
System.out.println(input + " is not a palindrome.");
}

scanner.close();
}

// Method to check if a string is a palindrome


public static boolean isPalindrome(String str) {
int left = 0;
int right = str.length() - 1;

while (left < right) {


if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}
Slip25b & slip26b: Create a package named Series having three different classes to print series:
i. Fibonacci series
ii. Cube of numbers
iii. Square of numbers
Write a java program to generate ‘n’ terms of the above series.
Step 1: Create the Package and Classes
1. Create the Directory Structure for the Package:
Series/
CubeSeries.java
SquareSeries.java

2. CubeSeries.java:
package Series;

public class CubeSeries {


public void printCubes(int n) {
System.out.print("Cubes of numbers: ");
for (int i = 1; i <= n; i++) {
System.out.print((i * i * i) + " ");
}
System.out.println();
}
}

3. SquareSeries.java:
package Series;

public class SquareSeries {


public void printSquares(int n) {
System.out.print("Squares of numbers: ");
for (int i = 1; i <= n; i++) {
System.out.print((i * i) + " ");
}
System.out.println();
}
}

Step 2: Create the Main Program


1. Main.java:
import Series.CubeSeries;
import Series.SquareSeries;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of terms (n): ");
int n = scanner.nextInt();

CubeSeries cube = new CubeSeries();


cube.printCubes(n);

SquareSeries square = new SquareSeries();


square.printSquares(n);

scanner.close();
}
}

Step 3: Compile and Run the Program


javac Series/*.java Main.java
java Main
Slip27a & Slip28a: Write a java program to count the number of integers from a given list. (Use
Command line arguments).
CODE:
public class CountIntegers {
public static void main(String[] args) {
int count = 0;

for (String arg : args) {


try {
Integer.parseInt(arg); // Attempt to parse the argument as an integer
count++; // If successful, increment the count
} catch (NumberFormatException e) {
// Not an integer, do nothing
}
}

System.out.println("Number of integers: " + count);


}
}
Slip28b: Write a java Program to accept the details of 5 employees (Eno, Ename, Salary) and
display it onto the JTable.
Step 1: Create the Employee Class
class Employee {
private int eno;
private String ename;
private double salary;

public Employee(int eno, String ename, double salary) {


this.eno = eno;
this.ename = ename;
this.salary = salary;
}

public int getEno() {


return eno;
}

public String getEname() {


return ename;
}

public double getSalary() {


return salary;
}
}

Step 2: Create the Main Program with GUI


import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class EmployeeDetails {

private JFrame frame;


private JTextField enoField, enameField, salaryField;
private DefaultTableModel tableModel;

public EmployeeDetails() {
frame = new JFrame("Employee Details");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 400);
frame.setLayout(new BorderLayout());
// Panel for input fields
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new GridLayout(4, 2));

inputPanel.add(new JLabel("Employee Number:"));


enoField = new JTextField();
inputPanel.add(enoField);

inputPanel.add(new JLabel("Employee Name:"));


enameField = new JTextField();
inputPanel.add(enameField);

inputPanel.add(new JLabel("Salary:"));
salaryField = new JTextField();
inputPanel.add(salaryField);

JButton addButton = new JButton("Add Employee");


inputPanel.add(addButton);

frame.add(inputPanel, BorderLayout.NORTH);

// Table to display employee details


String[] columnNames = {"Employee Number", "Employee Name", "Salary"};
tableModel = new DefaultTableModel(columnNames, 0);
JTable table = new JTable(tableModel);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);

addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addEmployee();
}
});

frame.setVisible(true);
}

private void addEmployee() {


try {
int eno = Integer.parseInt(enoField.getText());
String ename = enameField.getText();
double salary = Double.parseDouble(salaryField.getText());

Employee employee = new Employee(eno, ename, salary);


tableModel.addRow(new Object[]{employee.getEno(), employee.getEname(),
employee.getSalary()});

// Clear input fields


enoField.setText("");
enameField.setText("");
salaryField.setText("");
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(frame, "Please enter valid numbers for Employee Number and
Salary.", "Input Error", JOptionPane.ERROR_MESSAGE);
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> new EmployeeDetails());
}
}
Slip11a & Slip30a: Write a java program to accept a number from a user, if it is zero then throw user
defined Exception “Number is Zero”. If it is non-numeric then generate an error “Number is Invalid”
otherwise check whetherit is palindrome or not.

import java.util.Scanner;

public class SimplePalindromeChecker {

public static void main(String[] args) {


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

// Check if input is numeric


if (!isNumeric(input)) {
System.out.println("Number is Invalid");
return;
}

int number = Integer.parseInt(input);

// Check if the number is zero


if (number == 0) {
System.out.println("Number is Zero");
return;
}

// Check if the number is a palindrome


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

scanner.close();
}

// Method to check if a string is numeric


private static boolean isNumeric(String str) {
return str.matches("-?\\d+");
}

private static boolean isPalindrome(int number) {


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

You might also like