Java Tutorial
Queue - first in first out
import java.util.*; class Jqueue{ public int count = 0; public int element; Scanner Sc=new Scanner(System.in); int n=Sc.nextInt(); int []a=new int[n]; void enqueue() { try { System.out.print("Enter the element: "); a[count++]=Sc.nextInt(); } catch(Exception e) { System.out.println(e+ "the queue is full"); } } void dequeue() { try { System.out.println("the deleted element is"+a[0]); for(int i=0; i<count-1; i++) { a[i] = a[i+1]; } a[count-1] =0; count -= 1; } catch(Exception e) { System.out.println(e +"the queue is empty"); } } void display() { try { for(int i=0;i<count;++i) { System.out.println("Elements in queue are" + a[i]); } } catch(Exception j) { System.out.println(j+"the queue is empty"); } } } class queue { public static void main(String args[]) { int opt,v; Scanner S=new Scanner(System.in); System.out.println("Enter queue size: "); Jqueue A=new Jqueue(); System.out.println("\nqueue\n1.enqueue\n2.dequeue\n3.display"); do { System.out.println("Enter the choice"); opt=S.nextInt(); switch(opt) { case 1: A.enqueue(); break; case 2: A.dequeue(); break; case 3: A.display(); break; default: System.out.println("invalid"); break; } System.out.println("do you wish to contnue(1/0)?"); v=S.nextInt(); }while(v==1); } }Output:
$ javac queue.java $ java queue Enter queue size: 5 queue 1.enqueue 2.dequeue 3.display Enter the choice 1 Enter the element: 23 do you wish to contnue(1/0)? 1 Enter the choice 1 Enter the element: 32 do you wish to contnue(1/0)? 1 Enter the choice 1 Enter the element: 56 do you wish to contnue(1/0)? 1 Enter the choice 3 Elements in queue are23 Elements in queue are32 Elements in queue are56 do you wish to contnue(1/0)? 1 Enter the choice 2 the deleted element is23 do you wish to contnue(1/0)? 1 Enter the choice 2 the deleted element is32 do you wish to contnue(1/0)? 1 Enter the choice 2 the deleted element is56 do you wish to contnue(1/0)? 1 Enter the choice 2 the deleted element is0 java.lang.ArrayIndexOutOfBoundsException: -1the queue is empty do you wish to contnue(1/0)?
Java Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page