TOPIC REVERSE POLISH (HP) STYLE CALCULATOR - PART 2

profilehelp55
BIT-210ASReversePolishHPStyleCalculator.Part1.docx

package Arraystack;

public class ArrayStack

{

private double[] array;

private int size;

private int num;

public ArrayStack(int a){

array = new double[a];

size = a;

num = 0;

}

public void push(double a){

if (num < size){

array[num] = a;

num++;

System.out.println("Success");

}

else {

System.out.println("Failure! Stack is full");

}

}

public double pop(){

if (num > 0){

num--;

return array[num];

}

else {

System.out.println("Stack is empty");

return -1;

}

}

public boolean isEmpty(){

return (num == 0);

}

public double peek(int n){

try

{

if (num > 0)

{

if (n < 0 || n >= num)

return -1;

else

return array[num-1-n];

}

else

{

System.out.println("Stack is empty");

return -1;

}

}

catch(Exception e ){

e.printStackTrace();

}

return 0;

}

public int count(){

return num;

}

}

package TestArraystack;

import java.util.Scanner;

import Arraystack.ArrayStack;

public class TestArrayStack {

public static void main(String [] args)

{

int choice;

int pek;

double val,poped;

boolean empty;

Scanner sc =new Scanner(System.in);

ArrayStack as = new ArrayStack(20);

while(true){

System.out.println("1. Enter a Value in stack");

System.out.println("2. Pop a Value");

System.out.println("3. Check If array is Empty");

System.out.println("4. Peek Function");

System.out.println("5. Exit\n");

choice = sc.nextInt();

switch(choice)

{

case 1:

System.out.print("Enter a value To push : ");

val = sc.nextDouble();

as.push(val);

break;

case 2:

poped = as.pop();

System.out.println("Popped : "+poped);

break;

case 3:

empty = as.isEmpty();

System.out.println("Empty ? "+empty);

break;

case 4:

System.out.print("Enter a index to peek : ");

pek = sc.nextInt();

poped = as.peek(pek);

if(poped != -1)

System.out.println("Peeked Value : "+poped);

else

System.out.println("Oops it was not a valid index this place is empty");

break;

case 5:

System.exit(0);

}

}

}

}