0% found this document useful (0 votes)
51 views36 pages

LAB Manual

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)
51 views36 pages

LAB Manual

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/ 36

Experiment -1

Use Eclipse or Net bean platform and acquaint 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 atleast one if else condition and a for loop.

Procedure:-
STEP 1 : - Open any browser and search for Eclipse or Netbean IDE.

STEP 2 : - Open website of Eclipse or Netbean IDE and download the executable file(.exe) or rar file with
your operating system matched bit processor(32 or 64 bit). Download only the suitable file.

NOTE :- In some systems is necessary to set java Class Path and Java home path.

STEP 3 : - Install the eclipse or Netbean IDE, after completion of installation your ready to use the
IDE(Integrated Development Environment).

HOW RUN A SMAPLE PROGRAM IN JAVA USING ECLIPSE SOFTWARE.

STEP 1 : - Open Eclipse software, a welcome prompt or window is displayed.

STEP 2 : - At the top right corner you will have a File option, click on new option and then New Project
option.

STEP 3 : - A new window will be pop up and you need to name the Project eg:- CSE. Make sure that the
module is also given, if module name is not given it arises error at compile time. For naming the module
a specific box is given below the New Project Naming box.

STEP 4 : - At the top right corner below you will be having an option called Project Explorer. All the
projects can be viewed there including with your newly created project.

STEP 5 : - left click or right click on that project a small window will be pop’s, click on new and click on
class to create new class.

STEP 6 : - Name the class name and select the main method and click on ok, a new class file will be seen
at the screen.

STEP 7 : - Make the code in the main method and click on run button to execute the project.

Sample program with for and if loops

package heloo;

public class Forloopp {

public static void main(String[] args) {


int X=10;
if(X >=10)
{
System.out.println("X value is greater than 9");
}
else
{
System.out.println("X is not in range");
}
for(int i=0;i<=10;i++)
{
System.out.println("i value is" +i);

Refactor is used to rename the classes, interfaces, members and also Extraction.

Press F11 for debug or click on run option and select the debug option.

EXPERIMENT -2

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.

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

class BuildCalculator 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 = "=";

BuildCalculator() {

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("NRCM");

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 BuildCalculator();

EXPERIMENT -3

a) Develop an applet in Java that displays a simple message.

b) Develop an applet in Java that receives an integer in one text field and computes its factorial Value
and returns it in another text field, when the button named “Compute” is clicked.

EXPERIMENT -4

Write a Java program that creates a user interface to perform integer divisions. The user enters two
numbers in the text fields, Num1 and Num2. The division of Num1 and Num 2 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.

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

import javax.swing.event.*;

class A extends JFrame implements ActionListener { JLabel l1, l2, l3;

JTextField tf1, tf2, tf3; JButton b1;

A() {

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout());

l1 = new JLabel("Welcome"); setSize(800, 400);

l1 = new JLabel("Enter Number1"); add(l1);

tf1 = new JTextField(10); add(tf1);

l2 = new JLabel("Enter Number2"); add(l2);

tf2 = new JTextField(10); add(tf2);

l3 = new JLabel("Result"); add(l3);

tf3 = new JTextField(10);


add(tf3);

b1 = new JButton("Divide"); add(b1); b1.addActionListener(this); setVisible(true);

public void actionPerformed(ActionEvent ae) { try {

int a = Integer.parseInt(tf1.getText()); int b = Integer.parseInt(tf2.getText()); if(b==0)

throw new ArithmeticException(" Divide by Zero Error"); float c = (float) a / b;

tf3.setText(String.valueOf(c));

} catch (NumberFormatException ex) { JOptionPane.showMessageDialog(this, ex.getMessage());

} catch (ArithmeticException ex) { JOptionPane.showMessageDialog(this, ex.getMessage());

public class Num

public static void main(String[] args)

A a = new A();

EXPERIMENT -5

Write a Java program that implements a multi-thread application that has three threads. First thread
generates random integer every 1 second and if the value is even, second thread computes the square
of the number and prints. If the value is odd, the third thread will print the value of cube of the number.

package multithread;

import java.util.*;
// class for Even Number

class EvenNum implements Runnable {

public int a;

public EvenNum(int a) {

this.a = a;

public void run() {

System.out.println("The Thread "+ a +" is EVEN and Square of " + a + " is : " + a * a);

} // class for Odd Number

class OddNum implements Runnable {

public int a;

public OddNum(int a) {

this.a = a;

public void run() {

System.out.println("The Thread "+ a +" is ODD and Cube of " + a + " is: " + a * a * a);

// class to generate random number

class RandomNumGenerator extends Thread {

public void run() {

int n = 0;

Random rand = new Random();

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

n = rand.nextInt(20);

System.out.println("Generated Number is " + n);

// check if random number is even or odd

if (n % 2 == 0) {

Thread thread1 = new Thread(new EvenNum(n));

thread1.start();

else {

Thread thread2 = new Thread(new OddNum(n));

thread2.start();

// thread wait for 1 second

Thread.sleep(1000);

System.out.println("------------------------------------");

catch (Exception ex) {

System.out.println(ex.getMessage());

// Driver class

public class MultiThread {

public static void main(String[] args) {


RandomNumGenerator rand_num = new RandomNumGenerator();

rand_num.start();

EXPERIMENT-6

Write a Java program for the following: Create a doubly linked list of elements. Delete a given element
from the above list. Display the contents of the list after deletion.

package dbllist;

import java.util.*;

public class DoubleLinkedlist {

public static void main(String[] args) {

int i,ch,element,position;

LinkedList<Integer> dblList = new LinkedList<Integer>();

System.out.println("1.Insert element at begining");

System.out.println("2.Insert element at end");

System.out.println("3.Insert element at position");

System.out.println("4.Delete a given element");

System.out.println("5.Display elements in the list");

System.out.println("6.Exit");

Scanner sc=new Scanner(System.in);

do {

System.out.print("Choose your choice(1 - 6) :");

ch=sc.nextInt();

switch(ch) {
case 1: // To read element form the user

System.out.print("Enter an element to insert at begining : ");

element=sc.nextInt();

// to add element to doubly linked list at begining

dblList.addFirst(element);

System.out.println("Successfully Inserted");

break;

case 2: // To read element form the user

System.out.print("Enter an element to insert at end : ");

element=sc.nextInt();

// to add element to doubly linked list at end

dblList.addLast(element);

System.out.println("Successfully Inserted");

break;

case 3: // To read position form the user

System.out.print("Enter position to insert element : ");

position=sc.nextInt();

// checks if the position is lessthan or equal to list size.

if(position<=dblList.size()) {

// To read element

System.out.print("Enter element : ");

element=sc.nextInt();

// to add element to doubly linked list at given position

dblList.add(position,element);

System.out.println("Successfully Inserted");
}

else {

System.out.println("Enter the size between 0 to"+dblList.size());

break;

case 4: // To read element form the user to remove

System.out.print("Enter element to remove : ");

Integer ele_rm;

ele_rm=sc.nextInt();

if (dblList.contains(ele_rm)){

dblList.remove(ele_rm);

System.out.println("Successfully Deleted");

Iterator itr=dblList.iterator();

System.out.println("Elements after deleting :"+ele_rm);

while(itr.hasNext()) {

System.out.print(itr.next()+"<->");

System.out.println("NULL");

else {

System.out.println("Element not found");

break;

case 5: // To Display elements in the list


Iterator itr=dblList.iterator();

System.out.println("Elements in the list :");

while(itr.hasNext()) {

System.out.print(itr.next()+"<->");

System.out.println("NULL");

break;

case 6: System.out.println("Program terminated");

break;

default:System.out.println("Invalid choice");

while(ch!=6);

EXPERIMENT - 7

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 selected color. Initially, there is no message shown.

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

import java.awt.event.*;

class A extends JFrame implements ItemListener

public JLabel l1, l2;

public JRadioButton r1, r2, r3; public ButtonGroup bg; public JPanel p, p1;
public A()

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new GridLayout(2, 1));

setSize(800, 400);

p = new JPanel(new FlowLayout()); p1 = new JPanel(new FlowLayout()); l1 = new JLabel();

Font f = new Font("Verdana", Font.BOLD, 60); l1.setFont(f);

add(l1);

p.add(l1);

add(p);

l2 = new JLabel("Select Lights"); p1.add(l2);

JRadioButton r1 = new JRadioButton("Red Light");

r1.setBackground(Color.red); p1.add(r1); r1.addItemListener(this);

JRadioButton r2 = new JRadioButton("Yellow Light"); r2.setBackground(Color.YELLOW);

p1.add(r2); r2.addItemListener(this);

JRadioButton r3 = new JRadioButton("Green Light"); r3.setBackground(Color.GREEN);

p1.add(r3); r3.addItemListener(this); add(p1);

bg = new ButtonGroup(); bg.add(r1);

bg.add(r2);

bg.add(r3); setVisible(true);

public void itemStateChanged(ItemEvent i)

JRadioButton jb = (JRadioButton) i.getSource();

switch (jb.getText())

{
case "Red Light":

l1.setText("STOP"); l1.setForeground(Color.RED);

break;

case "Yellow Light":

l1.setText("Ready"); l1.setForeground(Color.YELLOW);

break;

case "Green Light":

l1.setText("GO"); l1.setForeground(Color.GREEN);

break;

public class TLights

public static void main(String[] args)

A a = new A();

}
Experiment-8

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 print Area (
) that prints the area of the given shape.

package areaofrectangle;

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 AORec {

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");

EXPERIMENT – 9

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.

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

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

class A extends JFrame

public A()

setSize(800, 800); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); GridLayout g = new GridLayout(0,


3);

setLayout(g);

try

FileInputStream fin = new FileInputStream("D:\\tablee.txt");

Scanner sc = new Scanner(fin).useDelimiter(",");


String[] arrayList;

String a;

while (sc.hasNextLine())

a = sc.nextLine();

arrayList = a.split(",");

for (String i : arrayList)

add(new JLabel(i));

} catch (Exception ex) {

setDefaultLookAndFeelDecorated(true); pack();

setVisible(true);

public class Tabledemo {

public static void main(String[] args) { A a = new A();

Experiment -10

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).

import javax.swing.*; import java.awt.*;

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


class A extends JFrame implements MouseListener

JLabel l1; public A()

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 400);

setLayout(new GridBagLayout()); l1 = new JLabel();

Font f = new Font("Verdana", Font.BOLD, 20); l1.setFont(f);

l1.setForeground(Color.BLUE); l1.setAlignmentX(Component.CENTER_ALIGNMENT);
l1.setAlignmentY(Component.CENTER_ALIGNMENT); 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 class Mevents { public static void main(String[] args) { A a = new A();

EXPERIMENT-11

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).

package namesphone;

import java.io.*;

import java.util.*;

public class Namephnum

public static void main(String args[])

try

FileInputStream fis=new FileInputStream("D:\\Table.txt");

Scanner sc=new Scanner(fis).useDelimiter("\t");

Hashtable<String,String> ht=new Hashtable<String,String>();


String[] strarray;

String a,str;

while(sc.hasNext())

a=sc.nextLine();

strarray=a.split("\t");

ht.put(strarray[0],strarray[1]);

System.out.println("hash table values are"+strarray[0]+":"+strarray[1]);

Scanner s=new Scanner(System.in);

System.out.println("Enter the name as given in the phone book");

str=s.next();

if(ht.containsKey(str))

System.out.println("phone no is"+ht.get(str));

else

System.out.println("Name is not matched");

catch(Exception e)

System.out.println(e);

}
}

EXPERIMENT-12

12. Write a Java program that correctly implements the producer – consumer problem using the
concept of inter thread communication.

package prdcrconscr;

class Thread1

int n;

boolean valueset=false;

synchronized int get()

if (!valueset)

try

wait();

catch (Exception e)

System.out.println("Excepton occur at :"+e);

System.out.println("get" +n);

try

{
Thread.sleep(1000);

catch (Exception e)

System.out.println("Excepton occur at : "+e);

valueset=false;

notify();

return n;

synchronized int put(int n)

if (valueset)

try

wait();

catch (Exception e)

System.out.println("Excepton occur at : " +e);

this.n=n;

valueset=true;

System.out.println("put" +n);

try
{

Thread.sleep(1000);

catch (Exception e)

System.out.println("Excepton occur at : " +e);

notify();

return n;

class Producer implements Runnable

Thread1 t;

Producer(Thread1 t)

this.t=t;

new Thread(this,"Producer").start();

public void run()

int i=0;

while (true)

t.put(i++);
}

class Consumer implements Runnable

Thread1 t;

Consumer(Thread1 t)

this.t=t;

new Thread(this,"Consumer").start();

public void run()

int i=0;

while (true)

t.get();

class Pdrcnsr

public static void main(String[] args)

Thread1 t=new Thread1();


new Producer(t);

new Consumer(t);

System.out.println("Press Control+c to exit");

EXPERIMENT-13

Write a Java program to list all the files in a directory including the files present in all its sub directories.

package listdict;

import java.io.File;

public class ListDict

public void printFileNames(File[] a, int i, int lvl)

// base case of the recursion

// i == a.length means the directory has

// no more files. Hence, the recursion has to stop

if(i == a.length)

return;

// tabs for providing the indentation

// for the files of sub-directory

for (int j = 0; j < lvl; j++)

{
System.out.print("\t");

// checking if the encountered object is a file or not

if(a[i].isFile())

System.out.println(a[i].getName());

// for sub-directories

else if(a[i].isDirectory())

System.out.println("[" + a[i].getName() + "]");

// recursion for sub-directories

printFileNames(a[i].listFiles(), 0, lvl + 1);

// recursively printing files from the directory

// i + 1 means look for the next file

printFileNames(a, i + 1, lvl);

// Main Method

public static void main(String[] argvs)

// Providing the full path for the directory

String path = "D:\\0 SUBJECTS";

// creating a file object

File fObj = new File(path);


// creating on object of the class DisplayFileExample1

ListDict obj = new ListDict();

if(fObj.exists() && fObj.isDirectory())

// array for the files of the directory pointed by fObj

File a[] = fObj.listFiles();

// display statements

System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");

System.out.println("Displaying Files from the directory: " + fObj);

System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");

// Calling the method

obj.printFileNames(a, 0, 0);

EXPERIMENT-14

Write a Java program that implements Quick sort algorithm for sorting a list of names in ascending order

package quicksort;

class Qsort

/* This function takes last element as pivot,

places the pivot element at its correct

position in sorted array, and places all

smaller (smaller than pivot) to left of


pivot and all greater elements to right

of pivot */

int partition(int arr[], int low, int high)

int pivot = arr[high];

int i = (low-1); // index of smaller element

for (int j=low; j<high; j++)

// If current element is smaller than or

// equal to pivot

if (arr[j] <= pivot)

i++;

// swap arr[i] and arr[j]

int temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

// swap arr[i+1] and arr[high] (or pivot)

int temp = arr[i+1];

arr[i+1] = arr[high];

arr[high] = temp;
return i+1;

/* The main function that implements QuickSort()

arr[] --> Array to be sorted,

low --> Starting index,

high --> Ending index */

void sort(int arr[], int low, int high)

if (low < high)

/* pi is partitioning index, arr[pi] is

now at right place */

int pi = partition(arr, low, high);

// Recursively sort elements before

// partition and after partition

sort(arr, low, pi-1);

sort(arr, pi+1, high);

/* A utility function to print array of size n */


static void printArray(int arr[])

int n = arr.length;

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

System.out.print(arr[i]+" ");

System.out.println();

// Driver program

public static void main(String args[])

int arr[] = {10, 7, 8, 9, 1, 5};

int n = arr.length;

Qsort ob = new Qsort();

ob.sort(arr, 0, n-1);

System.out.println("sorted array");

printArray(arr);

EXPERIMENT-15

Write a Java program that implements Bubble sort algorithm for sorting in descending order and also
shows the number of interchanges occurred for the given set of integers.

import java.util.Scanner;
public class Bsort {

public static void main(String[] args) {

int num, i, j, temp;

Scanner input = new Scanner(System.in);

System.out.println("Enter the number of integers to sort:");

num = input.nextInt();

int array[] = new int[num];

System.out.println("Enter " + num + " integers: ");

for (i = 0; i < num; i++)

array[i] = input.nextInt();

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

for (j = 0; j < num - i - 1; j++) {

if (array[j] < array[j+1])

temp = array[j];

array[j] = array[j+1];

array[j+1] = temp;

}
}

System.out.println("Sorted list of integers:");

for (i = 0; i < num; i++)

System.out.println(array[i]);

You might also like