Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

OOPS CODES

Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

1. Use Eclipse or NetBeans platform and acquaint yourself with the various menus.

Create a test
project, add a test class, and run it. See how you can use auto suggestions, auto fill. Try code
formatter and code refactoring like renaming variables, methods, and classes. Try debug step by
step with a small program of about 10 to 15 lines which contains at least one if else condition
and a for loop.
Program:
/* Sample java program to check given number is prime or not */
//Importing packages
import java.lang.System;
import java.util.Scanner;
// Creating Class
class Sample_Program {
// main method
public static void main(String args[]) {
int i,count=0,n;
// creating scanner object
Scanner sc=new Scanner(System.in);
// get input number from user
System.out.print("Enter Any Number : ");
n=sc.nextInt();
// logic to check prime or not
for(i=1;i<=n;i++) {
if(n%i==0) {
count++;
}
}
if(count==2)
System.out.println(n+" is prime");
else
System.out.println(n+" is not prime");
}
}
OUTPUT:
Enter Any Number : 10
10 is not prime
2. Write a Java program that implements a multi-thread application that has three threads. The first thread
generates a random integer every 1 second and if the value is even, the second thread computes the square
of the number and prints. If the value is odd, the third thread will print the value of the cube of the
number.
Program:
import java.util.*;
public class Multithreading
{
public static void main(String args[])
{
sample s=new sample();
s.start();
}
}
class even extends Thread
{
public int x;
public even(int num)
{ x=num;
}
public void run()
{
System.out.println("New thread "+x+" is even and square of "+x+" is : "+(x*x));
}
}
class odd extends Thread
{
public int x;
public odd(int num)
{x=num;
}
public void run()
{
System.out.println("New thread "+x+" is odd and cube of "+x+" is : "+(x*x*x));
}
}
class sample extends Thread
{
int num=0;
public void run()
{

Random r=new Random();

for(int i=1;i<=6;i++)
{
num=r.nextInt(200);
System.out.println("Mainthreadandgeneratednumberis"+num); try
{
if(num%2==0)
{
even e=new even(num);
e.start();
}
else
{
odd o=new odd(num);
o.start();
}
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println(" ");
}
}
}

OUTPUT:
3. write a Java program to create an abstract class named Shape that contains two integers and an empty
method named print Area (). Provide three classes named Rectangle, Triangle, and Circle such that each
one of the classes extends the class Shape. Each one of the classes contains only the method printArea ()
that prints the area of the given shape.
Program:
import java.util.*;
abstract class Shape {
public int x,y;
public abstract void printArea();
}
class Rectangle1 extends Shape {
public void printArea() {
float area;
area= x * y;
System.out.println("Area of Rectangle is " +area);
}
}
class Triangle extends Shape {
public void printArea() {
float area;
area= (x * y) / 2.0f;
System.out.println("Area of Triangle is " + area);
}
}
class Circle extends Shape {
public void printArea() {
float area;
area=(22 * x * x) / 7.0f;
System.out.println("Area of Circle is " + area);
}
}
public class AreaOfShapes {
public static void main(String[] args) {
int choice;
Scanner sc=new Scanner(System.in);
System.out.println("Menu \n 1.Area of Rectangle \n 2.Area of Traingle \n 3.Area of Circle ");
System.out.print("Enter your choice : ");
choice=sc.nextInt();
switch(choice) {
case 1: System.out.println("Enter length and breadth for area of rectangle : ");
Rectangle1 r = new Rectangle1();
r.x=sc.nextInt();
r.y=sc.nextInt();
r.printArea();
break;
case 2: System.out.println("Enter bredth and height for area of traingle : ");
Triangle t = new Triangle();
t.x=sc.nextInt();
t.y=sc.nextInt();
t.printArea();
break;
case 3: System.out.println("Enter radius for area of circle : ");
Circle c = new Circle();
c.x = sc.nextInt();
c.printArea();
break;
default:System.out.println("Enter correct choice");
}
}
}
OUTPUT:
4. Write a Java program that correctly implements the producer – consumer problem using the concept of
inter thread communication.
PROGRAM:
public class ProducerConsumerTest {
public static void main(String[] args) {
SharedResource s = new SharedResource();
Producer p1 = new Producer(s, 1);
Consumer c1 = new Consumer(s, 1);
p1.start();
c1.start();
}
}
class SharedResource {
private int contents;
private boolean available = false;

public synchronized int get() {


while (available == false) {
try {
wait();
} catch (InterruptedException e) {}
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value) {
while (available == true) {
try {
wait();
} catch (InterruptedException e) { }
}
contents = value;
available = true;
notifyAll();
}
}
class Consumer extends Thread {
private SharedResource s;
private int number;

public Consumer(SharedResource S, int number) {


s = S;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 10; i++) {
value = s.get();
System.out.println("Consumer #" + this.number + " got: " + value);
}
}
}
class Producer extends Thread {
private SharedResource s;
private int number;
public Producer(SharedResource S, int number) {
s = S;
this.number = number;
}
public void run() {
for (int i = 0; i < 10; i++) {
s.put(i);
System.out.println("Producer #" + this.number + " put: " + i);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
}
}
}
OUTPUT:
5. Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons for the
digits and for the +, -,*, % operations. Add a text field to display the result. Handle any possible
exceptions like divided by zero.
PROGRAM:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class SimpleCalculator extends JFrame implements ActionListener{


JFrame actualWindow;
JPanel resultPanel, buttonPanel, infoPanel;

JTextField resultTxt;
JButton btn_digits[] = new JButton[10];
JButton btn_plus, btn_minus, btn_mul, btn_div, btn_equal, btn_dot, btn_clear;
char eventFrom;

JLabel expression, appTitle, siteTitle ;

double oparand_1 = 0, operand_2 = 0;


String operator = "=";

SimpleCalculator() {
Font txtFont = new Font("SansSerif", Font.BOLD, 20);
Font titleFont = new Font("SansSerif", Font.BOLD, 30);
Font expressionFont = new Font("SansSerif", Font.BOLD, 15);

actualWindow = new JFrame("Calculator");


resultPanel = new JPanel();
buttonPanel = new JPanel();
infoPanel = new JPanel();

actualWindow.setLayout(new GridLayout(3, 1));


buttonPanel.setLayout(new GridLayout(4, 4));
infoPanel.setLayout(new GridLayout(3, 1));
actualWindow.setResizable(false);

appTitle = new JLabel("My Calculator");


appTitle.setFont(titleFont);
expression = new JLabel("Expression shown here");
expression.setFont(expressionFont);
siteTitle = new JLabel("CMRCET");
siteTitle.setFont(expressionFont);
siteTitle.setHorizontalAlignment(SwingConstants.CENTER);
siteTitle.setForeground(Color.BLUE);

resultTxt = new JTextField(15);


resultTxt.setBorder(null);
resultTxt.setPreferredSize(new Dimension(15, 50));
resultTxt.setFont(txtFont);
resultTxt.setHorizontalAlignment(SwingConstants.RIGHT);

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


btn_digits[i] = new JButton(""+i);
btn_digits[i].addActionListener(this);
}
btn_plus = new JButton("+");
btn_plus.addActionListener(this);
btn_minus = new JButton("-");
btn_minus.addActionListener(this);
btn_mul = new JButton("*");
btn_mul.addActionListener(this);
btn_div = new JButton("/");
btn_div.addActionListener(this);
btn_dot = new JButton(".");
btn_dot.addActionListener(this);
btn_equal = new JButton("=");
btn_equal.addActionListener(this);
btn_clear = new JButton("Clear");
btn_clear.addActionListener(this);

resultPanel.add(appTitle);
resultPanel.add(resultTxt);
resultPanel.add(expression);
for(int i = 0; i < 10; i++) {
buttonPanel.add(btn_digits[i]);
}
buttonPanel.add(btn_plus);
buttonPanel.add(btn_minus);
buttonPanel.add(btn_mul);
buttonPanel.add(btn_div);
buttonPanel.add(btn_dot);
buttonPanel.add(btn_equal);
infoPanel.add(btn_clear);
infoPanel.add(siteTitle);

actualWindow.add(resultPanel);
actualWindow.add(buttonPanel);
actualWindow.add(infoPanel);

actualWindow.setSize(300, 500);
actualWindow.setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
eventFrom = e.getActionCommand().charAt(0);
String buildNumber;
if(Character.isDigit(eventFrom)) {
buildNumber = resultTxt.getText() + eventFrom;
resultTxt.setText(buildNumber);
} else if(e.getActionCommand() == ".") {
buildNumber = resultTxt.getText() + eventFrom;
resultTxt.setText(buildNumber);
}
else if(eventFrom != '='){
oparand_1 = Double.parseDouble(resultTxt.getText());
operator = e.getActionCommand();
expression.setText(oparand_1 + " " + operator);
resultTxt.setText("");
} else if(e.getActionCommand() == "Clear") {
resultTxt.setText("");
}
else {
operand_2 = Double.parseDouble(resultTxt.getText());

expression.setText(expression.getText() + " " + operand_2);


switch(operator) {
case "+": resultTxt.setText(""+(oparand_1 + operand_2)); break;
case "-": resultTxt.setText(""+(oparand_1 - operand_2)); break;
case "*": resultTxt.setText(""+(oparand_1 * operand_2)); break;
case "/": try {
if(operand_2 == 0)
throw new ArithmeticException();
resultTxt.setText(""+(oparand_1 / operand_2)); break;
} catch(ArithmeticException ae) {
JOptionPane.showMessageDialog(actualWindow, "Divisor can not be ZERO");
}
}
}
}
}

public class Calculator {


public static void main(String[] args) {
new SimpleCalculator();
}
}
OUTPUT:

(OR)
PROGRAM:

/* Program to create a Simple Calculator */


import java.awt.*;
import java.awt.event.*;
public class MyCalculator extends Frame implements ActionListener {
double num1,num2,result;
Label lbl1,lbl2,lbl3;
TextField tf1,tf2,tf3;
Button btn1,btn2,btn3,btn4;
char op;
MyCalculator() {
lbl1=new Label("Number 1: ");
lbl1.setBounds(50,100,100,30);

tf1=new TextField();
tf1.setBounds(160,100,100,30);

lbl2=new Label("Number 2: ");


lbl2.setBounds(50,170,100,30);

tf2=new TextField();
tf2.setBounds(160,170,100,30);

btn1=new Button("+");
btn1.setBounds(50,250,40,40);

btn2=new Button("-");
btn2.setBounds(120,250,40,40);

btn3=new Button("*");
btn3.setBounds(190,250,40,40);

btn4=new Button("/");
btn4.setBounds(260,250,40,40);
lbl3=new Label("Result : ");
lbl3.setBounds(50,320,100,30);

tf3=new TextField();
tf3.setBounds(160,320,100,30);

btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
btn4.addActionListener(this);

add(lbl1); add(lbl2); add(lbl3);


add(tf1); add(tf2); add(tf3);
add(btn1); add(btn2); add(btn3); add(btn4);

setSize(400,500);
setLayout(null);
setTitle("Calculator");
setVisible(true);

public void actionPerformed(ActionEvent ae) {

num1 = Double.parseDouble(tf1.getText());
num2 = Double.parseDouble(tf2.getText());

if(ae.getSource() == btn1)
{
result = num1 + num2;
tf3.setText(String.valueOf(result));
}
if(ae.getSource() == btn2)
{
result = num1 - num2;
tf3.setText(String.valueOf(result));
}
if(ae.getSource() == btn3)
{
result = num1 * num2;
tf3.setText(String.valueOf(result));
}
if(ae.getSource() == btn4)
{
result = num1 / num2;
tf3.setText(String.valueOf(result));
}
}

public static void main(String args[]) {


MyCalculator calc=new MyCalculator();
}
}
OUTPUT:
6. A) Develop an applet in Java that displays a simple message.
PROGRAM:

/* Develop a applet to display the simple message */


import java.awt.*;
import java.applet.*;
/*<applet code="FirstApplet" width=400 height=300></applet>*/
public class FirstApplet extends Applet {
public void paint(Graphics g) {
g.setColor(Color.blue);
Font font = new Font("Arial", Font.BOLD, 16);
g.setFont(font);
g.drawString("This is My First Applet",60,110);
}
}
OUTPUT:

B) Develop an applet in Java that receives an integer in one textfield, and computes its factorial Value and
returns it in an other textfield, when the button named “Compute” is clicked.
PROGRAM:
/** Develop applet to find factorial of the given number */
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code="FactorialApplet" width=500 height=250>
</applet>*/
public class FactorialApplet extends Applet implements ActionListener {
Label L1,L2;
TextField T1,T2;
Button B1;
public void init() {
L1=new Label("Enter any Number : ");
add(L1);
T1=new TextField(10);
add(T1);
L2=new Label("Factorial of Num : ");
add(L2);
T2=new TextField(10);
add(T2);
B1=new Button("Compute");
add(B1);
B1.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==B1)
{
int value=Integer.parseInt(T1.getText());
int fact=factorial(value);
T2.setText(String.valueOf(fact));
}
}
int factorial(int n) {
if(n==0)
return 1;
else
return n*factorial(n-1);
}
}
OUTPUT:
7. Write a Java program that creates a user interface to perform integer divisions. The user enters two
numbers in the text fields, Num1and Num2. The division of Num1 and Num2 is displayed in the Result
field when the Divide button is clicked. If Num1 or Num2 were not an integer, the program would throw
a Number Format Exception. If Num2 were Zero, the program would throw an Arithmetic Exception.
Display the exception in a message dialog box.
PROGRAM:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class IntegerDivisions extends JFrame implements ActionListener {


JFrame actualWindow;
JPanel container;
JTextField txt_num1, txt_num2, txt_result;
JButton btn_div;

IntegerDivisions() {
actualWindow = new JFrame("Experiment 4");
container = new JPanel();
container.setLayout(new FlowLayout());
txt_num1 = new JTextField(20);
txt_num2 = new JTextField(20);
txt_result = new JTextField(20);

btn_div = new JButton("Divide");


btn_div.addActionListener(this);

container.add(txt_num1);
container.add(txt_num2);
container.add(btn_div);
container.add(txt_result);

actualWindow.add(container);
actualWindow.setSize(300, 300);
actualWindow.setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
int num1, num2;
try {
num1 = Integer.parseInt(txt_num1.getText());
num2 = Integer.parseInt(txt_num2.getText());
txt_result.setText(num1/num2+"");
}
catch(NumberFormatException nfe) {
JOptionPane.showMessageDialog(actualWindow,"Please do enter only integers");
}
catch(ArithmeticException ae) {
JOptionPane.showMessageDialog(actualWindow,"Divisor can not be ZERO");
}
}
}
public class Week_7 {

public static void main(String[] args) {


new IntegerDivisions();

}
OUTPUT:

8. Suppose that a table named Table.txt is stored in a text file. The first line in the file is the header, and
the remaining lines correspond to rows in the table. The elements are separated by commas. Write a java
program to display the table using Labels in Grid Layout.
PROGRAM:
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class Text_To_Table extends JFrame
{
public void convertTexttotable()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,300);
GridLayout g = new GridLayout(0, 4);
setLayout(g);
try
{
FileInputStream fis = new FileInputStream("./Table.txt");
Scanner sc = new Scanner(fis);
String[] arrayList;
String str;
while (sc.hasNextLine())
{
str = sc.nextLine();
arrayList = str.split(",");
for (String i : arrayList)
{
add(new Label(i));
}
}
}
catch (Exception ex) {
ex.printStackTrace();
}
setVisible(true);
setTitle("Display Data in Table");
}
}
public class TableText
{
public static void main(String[] args)
{
Text_To_Table tt = new Text_To_Table();
tt.convertTexttotable();
}
}
INPUT FORMAT:
NAME,NUMBER,MARKS,RESULT
NAVEEN,501,544,PASS
RAMESH,503,344,PASS
DURGA,521,344,PASS
ASHOK,532,344,PASS
MADHU,543,344,PASS
OUTPUT:
9. Write a Java program that simulates a traffic light. The program lets the user select one of three lights:
red, yellow, or green with radio buttons. On selecting a button, an appropriate message with “Stop” or
“Ready” or “Go” should appear above the buttons in the selected color. Initially, there is no message
shown.
PROGRAM:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class TrafficLightSimulator extends JFrame implements ItemListener {
JLabel lbl1, lbl2;
JPanel nPanel, cPanel;
CheckboxGroup cbg;
public TrafficLightSimulator() {
setTitle("Traffic Light Simulator");
setSize(600,400);
setLayout(new GridLayout(2, 1));
nPanel = new JPanel(new FlowLayout());
cPanel = new JPanel(new FlowLayout());
lbl1 = new JLabel();
Font font = new Font("Verdana", Font.BOLD, 70);
lbl1.setFont(font);
nPanel.add(lbl1);
add(nPanel);
Font fontR = new Font("Verdana", Font.BOLD, 20);
lbl2 = new JLabel("Select Lights");
lbl2.setFont(fontR);
cPanel.add(lbl2);
cbg = new CheckboxGroup();
Checkbox rbn1 = new Checkbox("Red Light", cbg, false);
rbn1.setBackground(Color.RED);
rbn1.setFont(fontR);
cPanel.add(rbn1);
rbn1.addItemListener(this);
Checkbox rbn2 = new Checkbox("Orange Light", cbg, false);
rbn2.setBackground(Color.ORANGE);
rbn2.setFont(fontR);
cPanel.add(rbn2);
rbn2.addItemListener(this);
Checkbox rbn3 = new Checkbox("Green Light", cbg, false);
rbn3.setBackground(Color.GREEN);
rbn3.setFont(fontR);
cPanel.add(rbn3);
rbn3.addItemListener(this);
add(cPanel);
setVisible(true);
// to close the main window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// To read selected item
public void itemStateChanged(ItemEvent i) {
Checkbox chk = cbg.getSelectedCheckbox();
String str=chk.getLabel();
char choice=str.charAt(0);
switch (choice) {
case 'R':lbl1.setText("STOP");
lbl1.setForeground(Color.RED);
break;
case 'O':lbl1.setText("READY");
lbl1.setForeground(Color.ORANGE);
break;
case 'G':lbl1.setText("GO");
lbl1.setForeground(Color.GREEN);
break;
}
}
// main method
public static void main(String[] args) {
new TrafficLightSimulator();
}
}
OUTPUT:
10. Write a Java program that loads names and phone numbers from a text file where the data is organized
as one line per record and each field in a record are separated by a tab (\t). It takes a name or phone
number as input and prints the corresponding other value from the hash table (hint: use hash tables).
PROGRAM:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;

public class HashTab {


public static void main(String[] args) {
HashTab prog11 = new HashTab();
Hashtable<String, String> hashData = prog11.readFromFile("HashTab.txt");
System.out.println("File data into Hashtable:\n" + hashData);
prog11.printTheData(hashData, "vbit");
prog11.printTheData(hashData, "123");
prog11.printTheData(hashData, " ");
}

private void printTheData(Hashtable<String, String> hashData, String input) {


String output = null;
if (hashData != null) {
Set<String> keys = hashData.keySet();
if (keys.contains(input)) {
output = hashData.get(input);
} else {
Iterator<String> iterator = keys.iterator();
while (iterator.hasNext()) {
String key = iterator.next();
String value = hashData.get(key);
if (value.equals(input)) {
output = key;
break;
}
}
}
}
System.out.println("Input given: " + input);

if (output != null) {
System.out.println("Data found in HashTable: " + output);
} else {
System.out.println("Data not found in HashTable");
}
}

private Hashtable<String, String> readFromFile(String fileName) {


Hashtable<String, String> hashData = new Hashtable<>();
BufferedReader br = null;
try {
File f = new File("D:\\java\\" + fileName);
br = new BufferedReader(new FileReader(f));
String line;
while ((line = br.readLine()) != null) {
String[] details = line.split("\t");
hashData.put(details[0], details[1]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return hashData;
}
}INPUT FORMAT:
HashTab.txt
cmrcet123
abc345
edrf 567
OUTPUT:
File data into Hashtable:
{123=vbit, 456=abc, 789=xyz}
Input given: vbit
Data found in HashTable: 123
Input given: 123
Data found in HashTable: vbit
Input given:
Data not found in HashTable
11. Write a Java program that handles all mouse events and shows the event name at the center of the
window when a mouse event is fired(Use Adapter classes).
PROGRAM:
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
class MouseEventPerformer extends JFrame implements MouseListener
{
JLabel l1;
public MouseEventPerformer()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
setLayout(new FlowLayout(FlowLayout.CENTER));
l1 = new JLabel();
Font f = new Font("Verdana", Font.BOLD, 20);
l1.setFont(f);
l1.setForeground(Color.BLUE);
add(l1);
addMouseListener(this);
setVisible(true);
}
public void mouseExited(MouseEvent m)
{
l1.setText("Mouse Exited");
}
public void mouseEntered(MouseEvent m)
{
l1.setText("Mouse Entered");
}
public void mouseReleased(MouseEvent m)
{
l1.setText("Mouse Released");
}
public void mousePressed(MouseEvent m)
{
l1.setText("Mouse Pressed");
}
public void mouseClicked(MouseEvent m)
{
l1.setText("Mouse Clicked");
}
public static void main(String[] args) {
MouseEventPerformer mep = new MouseEventPerformer();
}
}
OUTPUT:
12. Write a Java program to list all the files in a directory including the files present in all its sub
directories.
PROGRAM:
import java.util.Scanner;
import java.io.File;

public class ListingFiles {


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

// Prompt user for root directory


System.out.print("Enter the root directory name: ");
path = read.next() + ":\\";

File f_ref = new File(path);


if (!f_ref.exists()) {
printLine();
System.out.println("Root directory does not exist!");
printLine();
} else {
String ch = "y";
while (ch.equalsIgnoreCase("y")) {
printFiles(path);
System.out.print("Do you want to open any sub-directory (Y/N): ");
ch = read.next().toLowerCase();
if (ch.equalsIgnoreCase("y")) {
System.out.print("Enter the sub-directory name: ");
read.nextLine(); // Consume the leftover newline
String subDir = read.nextLine();
path = path + "\\" + subDir;

File f_ref_2 = new File(path);


if (!f_ref_2.exists() || !f_ref_2.isDirectory()) {
printLine();
System.out.println("The sub-directory does not exist!");
printLine();

// Revert to parent directory


int lastIndex = path.lastIndexOf("\\");
path = path.substring(0, lastIndex);
}
}
}
}

System.out.println("***** Program Closed *****");


read.close();
}
// Method to list files and directories
public static void printFiles(String path) {
System.out.println("Current Location: " + path);
File f_ref = new File(path);
File[] filesList = f_ref.listFiles();

if (filesList != null) {
for (File file : filesList) {
if (file.isFile())
System.out.println("- " + file.getName());
else
System.out.println("> " + file.getName());
}
} else {
System.out.println("The directory is empty or cannot be accessed.");
}
}

// Method to print a line separator


public static void printLine() {
System.out.println("----------------------------------------");
}
}
OUTPUT:

You might also like