exception handling in parentheses matching using stacks in java - 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

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

Creating a generic stack in generic stack class

I'm trying to teach myself some java and im stuck on a problem that seems kind of easy but i still don't seem to find a solution.
What I have so far:
Interface:
public interface ADTStack<T> {
public boolean isEmpty();
public void push(T element);
public T top() throws IllegalStateException;
public void pop() throws IllegalStateException;
}
Class Stack:
public class Stack<T> implements ADTStack<T> {
private java.util.LinkedList<T> data;
public Stack() {
data = new java.util.LinkedList<T>();
}
#Override
public boolean isEmpty() {
return data.isEmpty();
}
#Override
public void push(T element) {
data.add(0, element);
}
#Override
public T top() throws IllegalStateException {
if (isEmpty()) {
throw new IllegalStateException("Stack is emtpy.");
}
return data.getFirst();
}
#Override
public void pop() throws IllegalStateException {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty.");
}
data.remove(0);
}
Alright , so here is what I'm trying to do.
I'm trying to write a methode equals to compare two Stacks.
My idea was to use a third Stack to be able to bring both stacks into
their original state after comparing them.
Here's what I have:
Stack supportStack = new Stack();
public boolean equals(ADTStack<T> s){
if (data.isEmpty() != s.isEmpty()){
return false;
}
if (data.isEmpty() && s.isEmpty()){
return true;
}
T element_a = this.top();
T element_b = s.top();
if( (element_a ==null && (element_b !=null) || !element_a.equals(element_b) || element_a != null && element_b == null)){
return false;
}
data.pop();
s.pop();
supportStack.push(element_a);
boolean result = data.equals(s);
while (!supportStack.isEmpty()){
data.push(supportStack.top());
s.push(supportStack.top());
supportStack.pop();
}
return result;
}
I get a lot of errors when I compile the code and it seems that something is wrong with :
Stack supportStack = new Stack();
I don't really know what's wrong and how to solve the error. I made a runner-class and I tried the constructor and it worked so I'm confused at what's wrong.
public class Runner {
public static void main(String[] args){
Stack test = new Stack();
test.push(12);
System.out.println(test.top());
}
}
I gladly take any advice or constructive criticism since I'm teaching myself and if anything seems unclear feel free to ask.
Stack supportStack = new Stack();
Stack is called a raw type: it's like not using generics. You need to use:
Stack<T> supportStack = new Stack<T>();
But, as a hint: you don't need to do this. You can just do:
return this.data.equals( s.data );

how to use exceptions in a 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;
}
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");
}

Unhandled exception type SimulationException

My question is why I am still getting a Unhandled exception type SimulationExcpetion on calling damOverflowed() when that isn't declared in the interface for that method. The `levelTooLow method is declared in the interface and in the class and is fine. I added the interface methods at the bottom if that helps.
package asgn1Solution;
import asgn1Question.SimulationException;
import asgn1Question.Log;
import asgn1Question.Actions;
public class DamActions implements Actions{
private Integer capacity;
private Integer nomRelease;
private Integer duration;
private Log logging;
public DamActions(Integer damCapacity, Integer defaultRelease, Integer jobDuration, WaterLog damLog) {
capacity = damCapacity;
nomRelease = defaultRelease;
duration = jobDuration;
logging = damLog;
}
public boolean levelTooLow() throws SimulationException {
if (logging.getEntry(0) < capacity*.25) {
return true;
} else {
return false;
}
}
public boolean damOverflowed() {
if (logging.getEntry(0) > capacity) {
return true;
} else {
return false;
}
}
In Actions.java :
public boolean levelTooLow() throws SimulationException;
public boolean damOverflowed();
From your other question, in your WaterLog class you have declared the following method:
public Integer getEntry(Integer index) throws SimulationException {
if (thelog.isEmpty() || thelog.size() < index) {
return null;
}
return thelog.get(index);
}
The important thing to note here is the throws SimulationException clause in the method signature. This indicates that any method that calls getEntry must either handle a SimulationException or declare that it may be thrown*.
*This isn't strictly true, if the declared exception is an unchecked exception (i.e. a derivative of RuntimeException), then you aren't forced to handle it, even if you declare it in the throws clause. However, that you are getting compilation errors regarding this exception indicates that SimulationException is a checked exception, so does need to be handled or declared.
Thus, you have three options. First, you can enclose your call to getEntry in a try-catch block like so:
public boolean damOverflowed() {
try {
if (logging.getEntry(0) > capacity) {
return true;
} else {
return false;
}
} catch (SimulationException ex) {
// Do something here
}
}
Alternatively, you can declare that damOverflowed can also throw that exception:
public boolean damOverflowed() throws SimulationException {
Finally, as WaterLog#getEntry(Integer) doesn't actually appear to ever throw that exception (despite declaring that it can), your third option is to simply remove the declaration from the method signature:
public Integer getEntry(Integer index) {
if (thelog.isEmpty() || thelog.size() < index) {
return null;
}
return thelog.get(index);
}
I would also recommend reading through the Lesson: Exceptions tutorial from Oracle.

Categories