Pedro Mariz
Pedro Mariz

Reputation: 161

Array to Stack in java , and remove operators

I have one array (25*ax+c-d/2) and i want to put everything in a stack and next remove the operators ( *;+;-;/) and have at the end (25;ax;c;d) in a stack implementation.

Right now i have :

import java.util.*; 
  
public class StackDemo { 
    public static void main(String args[]) 
    { 
      	//Creating array
      	ArrayList<String> al = new ArrayList<String>();
      
      	//Adding to array
      	al.add("25*ax+c-d/2");
      
      	
      	//Creating a stack 
        Stack<String> STACK = new Stack<String>(); 
  
        //Adding array to stack 
        for(String str : al)
  			STACK.add(str);
  
        // Displaying the Stack 
        System.out.println("Initial Stack: " + STACK); 
  
    } 
} 

I know I'm grouping everything in the same stack position, but how can I separate and then remove the operators?

Upvotes: 0

Views: 8575

Answers (2)

Bogdan Kobylynskyi
Bogdan Kobylynskyi

Reputation: 1220

From JavaDoc reference of Stack class:

A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class.

Deque<String> stack = new ArrayDeque<String>();

In your scenario, it is possible to initialize a Deque by passing an ArrayList directly:

List<String> al = Arrays.asList("25*ax+c-d/2".split("[\\*+/-]"));
Deque<String> stack = new ArrayDeque<String>(al);

Upvotes: 0

H&#252;lya
H&#252;lya

Reputation: 3433

You can use regex to split the expression with operators:

public static void main(String[] args) {
    //Creating array
    List<String> al = Arrays.asList("25*ax+c-d/2".split("[\\*+/-]"));

    //Creating a stack 
    Stack<String> STACK = new Stack<String>(); 

    //Adding array to stack 
    for(String str : al)
        STACK.add(str);

    // Displaying the Stack 
    System.out.println("Initial Stack: " + STACK); 
}

Output:

Initial Stack: [25, ax, c, d, 2]

Upvotes: 1

Related Questions