Using Java Stack with String elements - java

I'm trying to use a java Stack to push String values:names into it, derived from input from a Scanner method. I'd then want to pop the names from the stack, and after show the logical and physical elements of the stack. I believe I should be using an Array Stack but not entirely sure as I don't have much quidance or experience with Stacks.
Currently I am getting the following error when compiling the Stack.java file.
Stack.java:24: cannot find symbol
symbol : method push(java.lang.String)
location: class java.lang.String[]
stack.push(s);
I've been researching this and trying different code for days, but as I am very new to this, and I have run out of ways to manipulate the code to make it work.
I would highly appreciate some advice...tnx!
Here is my Stack Class code:
import java.lang.*;
import java.util.*;
public class Stack { //Create Class
private String stack[] ;
private int top;
private static final int SIZE = 5;
String name;
Scanner scan = new Scanner(System.in);
public Stack(int SIZE){
stack = new String [SIZE];
top = 0;
}
public void push(String s) { //Method to Insert
if (isStackFull())
System.out.println ("Stack is Full "); //If Stack full Print Full
else {
while (scan.hasNextLine()){
s = scan.nextLine();
stack.push(s);
}
stack[top] = s;
top++;
}
}
public String pop() { //Method to Delete
if (isStackEmpty())
System.out.println ("Stack is Empty "); //If Stack empty print Empty
else{
String value = stack[top];
top--;
return value;
}
return stack[top];
}
public String toString( ){ //Method print Logical Stack
if (isStackEmpty( ))
System.out.println ("Stack is Empty "); //If Stack empty print Empty
else
System.out.println("\nThe Stack");
String result = "";
for (int j=0; j < top; j++)
result = result + stack[j].toString() + "\n";
return result;
}
public boolean isStackEmpty() { //Method boolean type to check empty Stack
return (top == 0);
}
public boolean isStackFull() { //Method boolean type to check full Stack
return (top == (SIZE-1));
}
}
For the StackTest Code, generally I call the methods in Stack. Eg.
public class StackTest { //Create class
public static void main(String[] args){ //Main Method
Stack n = new Stack(); //Declare variables
Scanner in = new Scanner(System.in);
String response;
char x;
and
while(x != 'q' && x != 'Q'){ //While loop initiates if no q or Q char input
switch(x){ //Start of swtich for insert, delete, print physical, logical or default quite
case 'i':
n.push();
System.out.println ("Inserted item from Stack");
break;
case 'd':
n.pop();
System.out.println ("Deleted item from Stack");
break;
case 'p':
n.toString();
System.out.println ("Printed Physical Stack ");
break;

Your push(String s) is method is calling push() on String which is incorrect, moreover the logic for push(String s) is complicated, rather it is simple as shown below in the code with comments:
public void push(String s) {
if (isStackFull())
System.out.println ("Stack is Full "); //If Stack full Print Full
else {
stack[top] = s; //just add the string to the top of the stack
top++; //increment top
}
}

In the push method itself you are trying to call stack.push hence it is throwing error. replace the stack.push to stack[top_index]= the string.

Related

receive multiple char input from a single line in java

I am writing a stack data structure in java using arrays. The problem is when I try to push the users char input it doesn't display. The problem is with this code.
public static void preSuf(Stack stack) {
Scanner key = new Scanner(System.in);
System.out.println("enter the values");
while(key.hasNext()){
char c = key.next().charAt(0);
stack.push(c);
}
}
When I change the while(key.hasNext()) to if(key.hasNext()) it works but it only prints one time and doesnt itterate. How can I fix this problem thank you.
Edit: Here is the whole code
import java.util.Scanner;
public class Stack {
private int top;
private char[] container;
private int size;
public static int pos = 0;
// constructor
public Stack(int N) {
container = new char[N];
size = N;
top = 0;
}
public boolean isFull() {
return (size == top);
}
public void push(char string) {
if (!isFull()) {
container[top] = string;
top++;
} else {
return;
}
}
public int pop() {
int drop;
drop = container[top - 1];
container[top] = 0;
top--;
return drop;
}
public int peek() {
int drop2;
drop2 = container[top - 1];
return drop2;
}
public void display() {
for (int i = 0; i < container.length; i++) {
if (container[i] != 0) {
System.out.print(container[i]);
}
}
}
public static void preSuf(Stack stack) {
Scanner key = new Scanner(System.in);
System.out.println("enter the values");
while(key.hasNext()){
char c = key.next().charAt(0);
stack.push(c);
}
}
public static void main(String args[]) {
Stack stack = new Stack(3);
preSuf(stack);
stack.display();
stack.display();
System.out.println();
}
}
The problem is that you haven't written any code to actually print the contents of your stack.
You could write a loop after your while loop to iterate over the stack and print out each character.
You'll also need a way of exiting your while loop. You can do this either with a special character, eg. if(c == '.') break; or you can just press Ctrl+Z.
EDIT: Based on the edit to the question and the full code being presented, I think the suggestion of needing the extra loop is now redundant. You have that in stack.display(). You just need to get out of your while loop.
you haven't determined when the loop should end.
you'd think if you press enter without entering anything the loop
would break but that's not how next operates. if you press enter
without entering anything or input data which consists of only whitespaces, next will block while waiting for input to
scan, even if a previous invocation of hasNext() returned true.
the solution is to include a condition at which control should break out of the loop.

Need to handle ArrayIndexOutOfBoundsException for stack array, without program ending

I am doing a pretty simple program, where a user will be prompted to enter up to 80 characters. We need to build our own stack and push each character onto the stack. Then pop and display the characters in reversed order. Thought I was done, but my instructor wants me to do something if a user enters more than 80 characters. Basically, I need to ignore all characters over 80. How would I go about doing this? I have been trying to figure this out, but can't get it. I am sure it will be something simple that I completely missed. Any help, suggestions, are appreciated!
stackUser
import java.util.Scanner;
public class stackUser {
public static void main(String[] args){
System.out.println("\nPlease enter up to 80 characters and I will reverse them: ");
Scanner key = new Scanner(System.in);
String input = key.nextLine();
myStack stack = new myStack();
for(int i = 0; i < input.length(); i++){
char c = input.charAt(i);
stack.push(c);
}
if(stack.isEmpty()){
System.out.println("Stack is empty!");
}else{
while(!stack.isEmpty()){
char rev = stack.pop();
System.out.print(rev);
}
}
}
}
myStack
public class myStack {
private int max = 80;
private char[] Stack = new char[max];
private int top = -1;
public void push(char input){
top++;
Stack[top] = input;
}
public char pop(){
char popped = Stack[top];
top --;
return popped;
}
public boolean isEmpty(){
boolean empty;
if(top == -1){
empty = true;
}else{
empty = false;
}
return empty;
}
}
Handle ArrayIndexOutOfBoundsException is bad idea, you need to check current top value with max value. Because ArrayIndexOutOfBoundsException is unchecked exception, and it means that error of developer.
I would declare the push method like this to indicate that it will throw an exception if the max is reached:
public void push(char input) throws ArrayIndexOutOfBoundsException{
top++;
Stack[top] = input;
}
Then in the main method you can use a try/catch block to handle the exception:
try{
stack.push(c);
}catch (ArrayIndexOutOfBoundsException ex){
System.out.println("too much!");
}
A try catch loop around anything that will throw an IndexOutOfBounds
try {
...code here
}
catch (ArrayIndexOutOfBoundsException e) {
...whatever you want to do in event of exception
}

Is there a way to add multiple strings to a stack without using a push method each time

I am working on a program to help student learn all the presidents in order. I am using a stack. I want to create a stack with all of the presidents in order. Then the user will enter a president name and the program will compare there input with the top of the stack.
I want to know if there is a way to fill my stack with Strings without using the .push method 44 times?
Here is what I have so far in my main:
package namepresidents;
import java.util.Scanner;
public class NamePresidents {
public static void main(String[] args)
{
BoundedStackInterface<String> presidents;
presidents = new ArrayStack<String>(41);
presidents.push("George Washington");
String menu = "Would you like to study: \n"
+ "1. All the presidents \n"
+ "2. The first half \n"
+ "3. The second half \n"
+ "0. Exit \n";
Scanner in = new Scanner(System.in);
int option = in.nextInt();
}
}
Here is my ArrayStack class for references:
package namepresidents;
public class ArrayStack<T> implements BoundedStackInterface<T> {
protected final int DEFCAP= 43;
protected T[] stack; //holds stack of elemets
protected int topIndex = -1;
public ArrayStack(){ // default constructor
stack = (T[]) new Object[DEFCAP];
}
public ArrayStack(int maxSize){ // constructor with user defined array size
stack = (T[]) new Object[maxSize];
}
public void push(T element){
//throws excption if the stack is full
//otherwise places element on top of stack
if (!isFull())
{
topIndex++;
stack[topIndex] = element;
}
else
{
throw new StackOverflowException("Push attempted on a full stack.");
}
}
public boolean isFull(){
//returns true if the stack is full
if (topIndex == stack.length-1)
{
return true;
}
else
{
return false;
}
}
public boolean isEmpty(){
//returns true if the stack is empty
if (topIndex == -1)
{
return true;
}
else
{
return false;
}
}
public void pop(){
//throws excption if the stack is full
//otherwise places element on top of stack
if (!isEmpty())
{
stack[topIndex] = null;
topIndex--;
}
else
{
throw new StackUnderflowException("Pop attempted on an empty stack.");
}
}
public T top(){
//throws excption if the stack is full
//otherwise returns element on top of stack
T topOfStack = null;
if (!isEmpty())
{
topOfStack = stack[topIndex];
}
else
{
throw new StackUnderflowException("Top attempted on an empty stack.");
}
return topOfStack;
}
}
Since the ArrayStack is a class that you implemented and it don't support that feature, your answer is no.
But you could add one push method to ArrayStack that accepte a list like this:
public void push(List<T> elements) {
for(T element : elements) {
push(element);
}
}

Syntax errors in parametrizing stacks

I'm a computer science student that just started my sophomore programming class and I'm having some real issues with a project that deals with Stacks and collections.
Basically, this is a project that relies on the ArrayStack Class(ArrayStack, to be specific) to convert mathematical expressions between postfix and infix forms.
Basically, ArrayStack is used to take in an expression like 45 * (26 - 5) / 54, turn it into a collection, then rewrite in a postfix form like 45 26 5 - * 54 /
The problem is, first of all, whenever I try to substitute with Character in the main method(since the stack needs to store both operators and operands, maybe there's a better data type I'm missing here), I get some strange syntax error, usually involving the program thinking that ArrayStack.System is somehow a statement(System.out.println is right below an ArrayStack statement, which suggests there's some kind of syntax problem)
Here's the code I have so far:
public class ArrayStack<T> implements StackADT<T>
{
private static final int DEFAULT_CAPACITY = 100;
private int top;
private T[] stack;
public ArrayStack() {
top = -1;
stack = (T[]) (new Object[DEFAULT_CAPACITY]);
}
public void push(T element) {
stack[top+1] = element;
top++;
}
public T pop() {
T element = stack[top];
stack[top] = null;
top--;
return element;
}
public T peek() {
return stack[top];
}
public boolean isEmpty() {
if(stack[0]==null)
return true;
else{
return false;
}
}
public int size() {
int length = 0;
for(int count=0;count<stack.length;count++) {
if(stack[count]!=null) {
length++;
}
else if(stack[count]==null) {
break;
}
}
return length;
}
public String toString() {
String array = "";
for(int count=0;count<stack.length;count++) {
array = array+stack[count]+" ";
}
return array;
}
}
And for the main method:
public class StackTester {
public static void main(String[] args) {
boolean quit = false;
int input;
String expression;
do {
System.out.println("1. Convert infix to postfix");
System.out.println("2. Convert postfix to infix");
System.out.println("3. Exit.");
java.util.Scanner keyboard = new java.util.Scanner(System.in);
input = keyboard.nextInt();
switch(input) {
case 1:
//ArrayStack stack = new ArrayStack();
//System.out.println("Enter an infix expression: ");
expression = keyboard.next();
for(int count=0;count<expression.length();count++) {
Character a = expression.charAt(count);
stack.push(a);
}
for(int count=stack.size()-1;count>=0;count--) {
if(stack.peek()=='+') {
}
}
}
break;
}
while(!quit);
}
}
The error usually occurs at the lines marked with //, every time I try to insert something like or otherwise, the program gives some weird syntax error like its trying to read it together with the line below it. Any ideas what's going on here?

Need help in implementing Java Algorithm on Postfix Evaluation

I've tried writing this code from scratch, coding, and running it but it just doesn't seem to work. This was assigned as lab work in class. The requirements are:
Implementing a postfix evaluation with the use of a stack and stack operations (user-defined).
I think the algorithm of my program is right, but it always gives me the wrong answer.
Here is my code.
public class StackApplication {
public static class Stack<T> {
private int top = 0;
private final static int stackMax=100;
// highest index of stk array
private Object[] stk = new Object[stackMax+1];
//Elements must be cast back.
public Stack() { // constructor
}
public boolean isEmpty(){
if (top==0) return true;
else return false;
}
public void push(T el) {
if(top==stackMax)
System.out.println("Stack push overflow error");
else top=top+1;
stk[top]=el;
}
public T pop(){
if(isEmpty()){
System.out.println("Stack push underflow error");
return null;
}
else top=top-1;
return(T)stk[top+1];
}
public T top(){
if(isEmpty()){
//System.out.println("Stack empty");
return null;
}
else return (T)stk[top];
}
}
public static boolean isOperator(char c){
return(c=='+' || c=='-' || c=='/' || c=='*' || c=='^');
}
public static double evaluate(double x, char o, double y) {
double result=0;
switch(o) {
case '+' : result=x+y; break;
case '-' : result=x-y; break;
case '*' : result=x*y; break;
case '/' : result=x/y; break;
case '^' : result=Math.pow(x, y); break;
default : break;
}
return result;
}
public static void main(String[] args) {
Scanner console=new Scanner(System.in);
Stack<Double> s=new Stack<Double>();
System.out.println("Input Postfix form to evaluate:");
String inp=console.nextLine();
char[] chararray=inp.toCharArray();
double b,a;
for(int i=0; i<chararray.length; i++) {
if(!isOperator(chararray[i]))
s.push((double)chararray[i]);
else {
b=s.pop();
a=s.pop();
double c=evaluate(a, chararray[i], b);
s.push(c);
}
}
System.out.println(" " +s.pop());
}
}
Sample Output:
Input Postfix form to evaluate:
23+ (Input)
101.0 (Output)
5.0 (Expected output)
The problem is here: s.push((double)chararray[i]);. You can't convert char to double this way. You are now taking the ascii code of 2 and 3.
50(ascii code of 2) + 51(ascii code of 3) = 101
Do it like this: s.push((double)(chararray[i] - '0'));
Your are doing the addition of the ASCII codes for 2 and 3, not of 2 and 3.
The code for 2 is 50 and for 3 is 51, so your out is 101, which is correct in this case.
When you push, push chararray[i]-'0'. This will solve your problem.

Categories