1

I have a string array that looks like this:

[67, +, 12, -, 45]

I want to print it out so that it looks like this:

67 12 + 45 -

Here's the code I'm trying to use to do this.

String[] temp = line.split(" ");
            String tmp = line.replaceAll("\\s+","");

            for(int i = 0; i < temp.length; i++)
            {
                if(isInt(temp[i]) == false)
                {
                    expression = temp[i];
                    firstExp = true;
                }
                else if(isInt(temp[i]) == false && firstExp == true && secondExp == false)
                {
                    System.out.print(expression);
                    secondExp = true;
                }
                else if(isInt(temp[i]) == false && firstExp == true && secondExp == true)
                {
                    System.out.print(expression);
                    firstExp = false;
                    secondExp = false;
                }
                else
                {
                    System.out.print(temp[i]);
                }
            }

firstExp and secondExp are Booleans that check for the expressions that should appear in the array. isInt() is just a method used to determine if the string is a number. Right now, all this code does is output this:

671245
16
  • Is there some rule to get to this result 67 12 + 45 - Commented Nov 26, 2013 at 3:46
  • Basically the rule is that it needs to print all the numbers related to the one expression first, then print the expression itself. Commented Nov 26, 2013 at 3:51
  • 1
    Do you need to handle invalid arrays, like [67, 45, -, - ]? Commented Nov 26, 2013 at 3:56
  • 1
    @JorgeCampos sorry edited...thats what i understand. Please correct if im wrong. Commented Nov 26, 2013 at 4:00
  • 1
    How about operator precedence? so [3, +, 4, *, 5] would be: 4 5 * 3 + ? Commented Nov 26, 2013 at 4:02

3 Answers 3

1
public static void main (String[] args) throws java.lang.Exception
    {
        String[] expr = new String[]{"67", "+", "45", "-", "12", "*", "5", "/", "78"};
        int current = 0;
        StringBuilder postfix = new StringBuilder();

        // handle first three
        postfix.append(expr[current]).append(" ");
        postfix.append(expr[current+2]).append(" ");
        postfix.append(expr[current+1]).append(" ");
        current += 3;

        // handle rest
        while( current <= expr.length-2 ){
            postfix.append(expr[current+1]).append(" ");
            postfix.append(expr[current]).append(" ");
            current += 2;
        }

        System.out.println(postfix.toString());
    }

Outputs:

67 45 + 12 - 5 * 78 /

You can run/edit this at: http://ideone.com/zcdlEq

Sign up to request clarification or add additional context in comments.

Comments

1

I guess what you are trying to do is converting infix expression to post fix. Some time back I had written the following code:

    public class InfixToPostfix {
   private Stack stack;
   private String input;
   private String output = "";
   public InfixToPostfix(String in) {
      input = in;
      int stackSize = input.length();
      stack = new Stack(stackSize);
   }
   public String translate() {
      for (int j = 0; j < input.length(); j++) {
         char ch = input.charAt(j);
         switch (ch) {
            case '+': 
            case '-':
            hastOperator(ch, 1); 
            break; 
            case '*': 
            case '/':
            hastOperator(ch, 2); 
            break; 
            case '(': 
            stack.push(ch);
            break;
            case ')': 
            hasSuperior(ch); 
            break;
            default: 
            output = output + ch; 
            break;
         }
      }
      while (!stack.isEmpty()) {
         output = output + stack.pop();
      }
      System.out.println(output);
      return output; 
   }
   public void hastOperator(char op, int precedence) {
      while (!stack.isEmpty()) {
         char opTop = stack.pop();
         if (opTop == '(') {
            stack.push(opTop);
            break;
         }
         else {
            int prec2;
            if (opTop == '+' || opTop == '-')
            prec2 = 1;
            else
            prec2 = 2;
            if (prec2 < precedence) { 
               stack.push(opTop);
               break;
            }
            else
            output = output + opTop;
         }
      }
      stack.push(op);
   }
   public void hasSuperior(char ch){ 
      while (!stack.isEmpty()) {
         char chx = stack.pop();
         if (chx == '(') 
         break; 
         else
         output = output + chx; 
      }
   }
   public static void main(String[] args) 
   throws IOException {
      String input = "67 + 12 - 45";
      String output;
      InfixToPostfix theTrans = new InfixToPostfix(input);
      output = theTrans.translate(); 
      System.out.println("Postfix is " + output + '\n');
   }
   class Stack {
      private int maxSize;
      private char[] stackArray;
      private int top;
      public Stack(int max) {
         maxSize = max;
         stackArray = new char[maxSize];
         top = -1;
      }
      public void push(char j) {
         stackArray[++top] = j;
      }
      public char pop() {
         return stackArray[top--];
      }
      public char peek() {
         return stackArray[top];
      }
      public boolean isEmpty() {
         return (top == -1);
     }
    }
    }

You may need to modify this program to read from an array, but that is very trivial.

Comments

1

Here's how you do it in one line:

System.out.println(Arrays.toString(temp).replaceAll("[^\\d +*/-]", "").replaceAll("[+*/-]) (\\d+)", "$2 $1"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.