how to use exceptions in a queue - java

public class ArrayQueue{
private Object[] theArray;
private int currentSize;
private int front;
private int rear;
static final int DEFAULT_CAPACITY=10;
public ArrayQueue(){
theArray=new Object[DEFAULT_CAPACITY];
makeEmpty();
}
public void makeEmpty(){
currentSize=0;
rear=-1;
front=0;
}
public void enqueue(Object x) throws OverFlow{
if (isFull())
throw new OverFlow("Array size exceeded");
else{
rear=increment(rear);
theArray[rear]=x;
currentSize++;
}
}
public Object dequeue()throws UnderFlow{
if (isEmpty())
throw new UnderFlow("Empty array");
else{
Object returnValue=theArray[front];
theArray[front]=null;//check if this has to be done
front=increment(front);
currentSize--;
return returnValue;
}
}
public Object getFront() throws UnderFlow{
if (isEmpty())
throw new UnderFlow("Empty array");
else
return theArray[front];
}
public boolean isEmpty(){
if (currentSize==0)
return true;
else
return false;
}
public boolean isFull(){
if (currentSize==theArray.length)
return true;
else
return false;
}
public int increment(int x){
if (x+1==currentSize)
x=0;
else
x++;
return x;
}
public static void main (String args[]){
ArrayQueue q=new ArrayQueue();
q.enqueue("1");
}
}
public class OverFlow extends Exception{
public OverFlow(){
super();
}
public OverFlow(String s){
super(s);
}
}
public class UnderFlow extends Exception{
public UnderFlow(){
super();
}
public UnderFlow(String s){
super(s);
}
}
When I try to run this I get an error as unreported exception OverFlow,Must be caught or declared to be thrown.
I am new to Java and programming but I have to learn a data structures course.Therefore if someone can tell me whats wrong here and how to correct it it would be really helpful

Any class that extends Exception (with the exception of RuntimeException) is considered a checked exception. This means that you, the programmer, must either catch it in a try...catch block, or throw the exception elsewhere.
The problem is that your method enqueue() throws a checked exception.
You could solve this one of two ways:
Wrap the call to enqueue in a try...catch block, or
Add throws OverFlow to main.
Examples of both:
try {
q.enqueue("1");
} catch (OverFlow e) {
e.printStackTrace();
}
public static void main(String[] args) throws OverFlow {
ArrayQueue q=new ArrayQueue();
q.enqueue("1");
}

Related

What is wrong with this code? It won't run

public class StackSimple{
private long capacity=1000;//maximum size of array
private int idx_top;
private Object data[];
public StackSimple(int capacity)
{
idx_top=-1;
this.capacity=capacity;
data = new Object[capacity];
}
public boolean isEmpty(){
return(idx_top<0);
}
public boolean isFull(){
return(idx_top>=capacity-1);
}
public int size()
{
return idx_top+1;
}
public boolean push(Object x){
if (isFull()){
throw new IllegalArgumentException("ERROR:Stack Overflow.Full Stack");
}
else
{`enter code here`data[++idx_top]=x;
return true;
}
}
public Object pop(){
if(isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else{
return data[idx_top--];
}
}
public Object top(){
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else{
return data[idx_top];
}
}
public void print()
{`
for (int i=size()-1;i>=0;i--)
System.out.println(data[i]);
}
}
public class Stack_Exercise {
public static void main(String[] args) {
StackSimple s = new StackSimple(capacity:3);//error shows here
s.push(x:"books");`enter code here`
s.push(x:"something");
s.push(x:"200");
s.print();
System.out.println("Size=" +s.size());
}
}
Why doesn't this work?
Why does it say invalid statement while creating the StackSimple object? The problem is in the main class while running it. There are errors while pushing the elements.
Error while compiling
When passing parameters to a function you just pass the values.
In your case not StackSimple(capacity:3) but just StackSimple(3)
First question, which version of Java are you using.
Second, in Java you should be passing as a variable instead of StackSimple(capacity:3). Change your main method to below, here is my recommendation:
StackSimple s = new StackSimple(3);
s.push("books");
s.push("something");
s.push("200");
s.print();
System.out.println("Size=" +s.size());
You are not at all pushing the value in the stack, your pusch function is not working as it is expected to work.
Here is the correct program.
class StackSimple {
private long capacity = 1000;// maximum size of array
private int idx_top;
private Object data[];
public StackSimple(int capacity) {
idx_top = -1;
this.capacity = capacity;
data = new Object[capacity];
}
public boolean isEmpty() {
return (idx_top < 0);
}
public boolean isFull() {
return (idx_top >= capacity - 1);
}
public int size() {
return idx_top + 1;
}
public boolean push(Object x) {
if (isFull()) {
throw new IllegalArgumentException("ERROR:Stack Overflow.Full Stack");
} else {
data[++idx_top] = x;
return true;
}
}
public Object pop() {
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else {
return data[idx_top--];
}
}
public Object top() {
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else {
return data[idx_top];
}
}
public void print() {
for (int i = size() - 1; i >= 0; i--)
System.out.println(data[i]);
}
}
public class test {
public static void main(String[] args) {
StackSimple s = new StackSimple(3);// error shows here
s.push("books");
s.push("something");
s.push("200");
s.print();
System.out.println("Size=" + s.size());
}
}

Get call in stack Java

public void push(E e)
{
list.add(e);
}
public E pop()
{
list.remove(list.size()-1);
}
public E peek()
{
}
public boolean empty()
{
if ( list.size()== 0)
{
return false;
}
else
{
return true;
}
}
This is part of a driver code my teacher gave me in order to under stand the stack. I understand what each part of the stack does, I am just not understanding how to implement the stack based on this code. I need help with the peek method mainly, but if you see other issues please let me know. I would appreciate the help.
public E peek(){
if(empty()) return null;
int top = list.size()-1;
return list.get(top);
}
AND empty method can be simplifized to:
public boolean empty(){
return list.size() == 0;
}
OR
public boolean empty(){
return list.isEmpty();
}
AND pop method should throws NoSuchElementException when stack is empty.
public E pop(){
if(empty()) throw new NoSuchElementException();
int top = list.size()-1;
return list.remove(top);
}

exception handling in parentheses matching using stacks in java

I am trying to write a program that checks for parentheses matching using stacks.This is my ArrayStack class.
public class ArrayStack{
private final int DEFAULT_SIZE=10;
public int tos;
Object[] array;
public ArrayStack(){
array =new Object[DEFAULT_SIZE];
tos=-1;
}
public void push(Object e)throws OverFlowException{
if (isFull()){
throw new OverFlowException("OverFlow");
}
else{
array[tos+1]=e;
tos++;
}
}
public Object topAndpop() throws EmptyStackException{
Object returnPop;
if (isEmpty())
throw new EmptyStackException("Stack empty");
else{
returnPop=top();
pop();
}
return returnPop;
}
public void pop() throws EmptyStackException{
if (isEmpty())
throw new EmptyStackException("Stack empty");
else
tos--;
}
public Object top() throws EmptyStackException{
if (isEmpty())
throw new EmptyStackException("Stack empty");
else
return array[tos];
}
public boolean isEmpty(){
return tos==-1;
}
public boolean isFull(){
if(tos==array.length)
return true;
else
return false;
}
public void makeEmpty() throws EmptyStackException{
while (tos>=0){
if (isEmpty())
throw new EmptyStackException("Stack empty");
else
pop();
}
}
public void print(){
for (int i=0;i<=tos;i++){
System.out.println(array[i]);
}
}
public static void main (String args[]) throws EmptyStackException,OverFlowException {
ArrayStack newStack=new ArrayStack();
newStack.push("S");
newStack.push("apple");
newStack.push("D");
newStack.topAndpop();
newStack.push("P");
newStack.print();
}
}
And this is my matching class.
public class Matching{
ArrayStack match_Stack=new ArrayStack();
Object popped;
Object[] array_match={"{","}"};
public boolean matching() {
for(int i=0;i< array_match.length;i++){
if (array_match[i]=="{" || array_match[i]=="[" ||array_match[i]=="(" )
match_Stack.push(array_match[i]);
if(array_match[i]=="}" || array_match[i]=="]" || array_match[i]==")"){
if (match_Stack.isEmpty())
return false;
if (match_Stack.topAndpop()==array_match[i]);
return true;
}
}
if (match_Stack.isEmpty())
return true;
else
return false;
}
public static void main (String args[]) throws EmptyStackException,OverFlowException {
}
}
This is EmptyStackException class :
public class EmptyStackException extends Exception{
public EmptyStackException(){
super();
}
public EmptyStackException(String s){
super(s);
}
public void print(){
System.out.println("OverFlow");
}
}
But the problem is when I compile matching I get an error as unreported exception EmptyStackException.must be caught or declared to be thrown.
I think the problem is with exceptions which I don't have a good knowledge of.I am stuck here for days and because of this exception issue I am unable to study the rest of data structures. So any help on how I can fix this and run this would be greatly helpful.
You really should read a tutorial about exceptions and work it through completely. This way you will get a better understanding of exceptions.
Your problem is the method Matching.matching(). You are using the methods ArrayStack.push(Object) and ArrayStack.topAndpop() in the method's implementation. But these methods are declared to (potentially) throw an EmptyStackException.
Your matching method does not deal with that exception. The exception must be either caught or thrown. This is what the compiler does tell you. So for a first coming-through declare the method as
public boolean matching() throws EmptyStackException

Queue exception handling

This my code for a circularly linked array based queue.
public class ArrayQueue{
private Object[] theArray;
private int currentSize;
private int front;
private int rear;
static final int DEFAULT_CAPACITY=10;
public ArrayQueue(){
theArray=new Object[DEFAULT_CAPACITY];
makeEmpty();
}
public void makeEmpty(){
currentSize=0;
rear=-1;
front=0;
}
public void enqueue(Object x) throws OverFlow{
if (isFull())
throw new OverFlow("Array size exceeded");
else{
rear=increment(rear);
theArray[rear]=x;
currentSize++;
}
}
public Object dequeue()throws UnderFlow{
if (isEmpty())
throw new UnderFlow("Empty array");
else{
Object returnValue=theArray[front];
theArray[front]=null;//check if this has to be done
front=increment(front);
currentSize--;
return returnValue;
}
}
public object getFront() throws UnderFlow{
if (isEmpty())
throw new UnderFlow("Empty array");
else
return theArray[front];
}
public boolean isEmpty(){
if (currentSize==0)
return true;
else
return false;
}
public boolean isFull(){
if (currentSize==theArray.length)
return true;
else
return false;
}
public int increment(int x){
if (x+1==currentSize)
x=0;
else
x++;
return x;
}
}
When I compiled this I get errors as cannot find symbol throw new OverFlow.
How to get rid of this issue.

Creating queue from two stacks

Can someone explain what am I doing wrong here ?
I am trying to create a queue from two stacks as per a book exercise. I get error "Stack Underflow" from the peek function. But everything seems right to me :P Please explain. Thanks!
//Program to implement Queue using two Stacks.
import java.util.NoSuchElementException;
public class Ex3_5_Stack {
int N;
int countOfNodes=0;
private Node first;
class Node {
private int item;
private Node next;
}
public Ex3_5_Stack() {
first=null;
N=0;
}
public int size() {
return N;
}
public boolean isEmpty() {
return first==null;
}
public void push(int item){
if (this.countOfNodes>=3) {
Ex3_5_Stack stack = new Ex3_5_Stack();
stack.first.item=item;
N++;
} else {
Node oldfirst = first;
first = new Node();
first.item=item;
first.next=oldfirst;
N++;
}
}
public int pop() {
if (this.isEmpty())
throw new NoSuchElementException("Stack Underflow");
int item = first.item;
first=first.next;
return item;
}
public int peek() {
if (this.isEmpty())
throw new NoSuchElementException("Stack Underflow");
return first.item;
}
}
And MyQueue file
public class Ex3_5_MyQueue {
Ex3_5_Stack StackNewest,StackOldest;
public Ex3_5_MyQueue() {
super();
StackNewest = new Ex3_5_Stack();
StackOldest = new Ex3_5_Stack();
}
public int size() {
return StackNewest.size()+StackOldest.size();
}
public void add(int value) {
StackNewest.push(value);
}
private void transferStack() {
if (StackOldest.isEmpty()) {
while (StackNewest.isEmpty()) {
StackOldest.push(StackNewest.pop());
}
}
}
public int peek() {
this.transferStack();
return StackOldest.peek();
}
public int remove() {
this.transferStack();
return StackOldest.pop();
}
public static void main(String[] args) {
Ex3_5_MyQueue myQueue = new Ex3_5_MyQueue();
myQueue.add(4);
myQueue.add(3);
myQueue.add(5);
myQueue.add(1);
System.out.println(myQueue.peek());
}
}
In transferStack(), you're missing an exclamation mark. It should be:
private void transferStack(){
if(StackOldest.isEmpty()){
while(!StackNewest.isEmpty()){ // you forgot it here
StackOldest.push(StackNewest.pop());
}
}
}

Categories