Results 1 to 3 of 3
Thread: Help me out..
- 03-06-2011, 06:58 AM #1
Member
- Join Date
- Mar 2011
- Posts
- 30
- Rep Power
- 0
Help me out..
import java.util.Scanner;
class queue
{
int a[]=new int[5];
int val,max;
int front=-1;
int rear=-1;
int currentsize=0;
int value;
queue(int len)
{
max=len;
}
void enque(int ele) throws MyException
{
if(rear==max-1)
{
throw new MyException("Array is overflow, value can not be inserted");
}
else if(front==-1&&rear==-1)
{
front++;
rear++;
a[rear]=ele;
}
else
{
rear++;
a[rear]=ele;
}
}
void deque() throws MyException
{
if(front==-1)
{
throw new MyException("Array is underflow");
}
else if(front==rear)
{
val=a[front];
front=rear=-1;
System.out.println("The deleted element:"+val);
}
else
{
val=a[front];
front++;
System.out.println("The deleted element:"+val);
currentsize=front;
}
}
void display()
{
for(int i=front;i<=rear;i++)
{
System.out.println("a["+i+"]="+a[i]);
}
}
}
public class show
{
public static void main(String args[])
{
int ch;
queue q=new queue(5);
Scanner S=new Scanner(System.in);
do
{
System.out.println("1.To insert in queue");
System.out.println("2.To Delete from queue");
System.out.println("3.To display queue");
System.out.println("4.Exit");
System.out.println("Enter the choice");
ch=S.nextInt();
switch(ch)
{
case 1: System.out.println("The value to be entered");
try
{
int ele=S.nextInt();
q.enque(ele);
}
catch(MyException e)
{
System.out.println(e);
}
break;
case 2:
try
{q.deque();}
catch(MyException e){System.out.println(e);}
break;
case 3:
q.display();
break;
case 4:System.exit(0);
break;
default:
System.out.println("Invalid");
}
}while(ch>1||ch<4);
}
}
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}
In this code i want to restrict the entered value must be integer only otherwise user defined exception must be raised..
- 03-06-2011, 11:09 AM #2
in your code your exception will not be thrown because when the user doesn't enter an int the default InputMismatchException will be thrown from int ele=S.nextInt() before the other lines of code are executed. so you must check for your own exception before the S.nextInt(). so changing your case 1 in
Java Code:case 1: System.out.print("The value to be entered"); if (S.hasNextInt()) { try { int ele = S.nextInt(); q.enque(ele); } catch (MyException e) { } } else { throw new MyException("Invalid value"); }
now the try block is only executed when S.hasNextInt() returns true and this will happen if the scanner find an int. if not the else block is executed and your MyException will be thrown.
- 03-07-2011, 04:11 AM #3
Member
- Join Date
- Mar 2011
- Posts
- 30
- Rep Power
- 0


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks