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

Java Solutions

Uploaded by

DEEPAK PAWAR
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Java Solutions

Uploaded by

DEEPAK PAWAR
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

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