Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostFixCalculator while/try error

Tags:

java

import java.util.Scanner;

public class PostFixCalculator
{
      public static void main(String [] args)
      {
            Scanner kbd = new Scanner(System.in);
            int result;
            String expression;

            System.out.println("Student name, CS-304, Fall 2014, Asst 2c.");

            System.out.println("To quit this program, just hit 'return'.\n");

            System.out.print("Enter a postfix expression: ");
            expression = kbd.nextLine();

         while (!expression.equals(""))
         {
               try
               {
               }
            catch(RuntimeException e)
            {
            }

            System.out.print("\nEnter a postfix expression: ");
            expression = kbd.nextLine();

         } // end while (!expression.equals(""))

         System.out.println("\nBye!");

      } // end public static void main(String [] args)


   public static int postFixEvaluate(String input)
   {
      Scanner tokenizer; 
      int result, operand1, operand2, value;
      String operator;
      LinkedStack s = new LinkedStack();

      tokenizer = new Scanner(input);

      while (tokenizer.hasNext())
      {
         if (tokenizer.hasNextInt())
         {
            value = tokenizer.nextInt();
            s.push(value);
         }

         else // we have an operator
         {
            operator = tokenizer.next();

            if (s.isEmpty())
                throw new RuntimeException ("Not Enough Operands");
                operand2 = s.pop();

            if (s.isEmpty())
                throw new RuntimeException ("Not Enough Operands");
                operand1 = s.pop();

            if (operator.equals("+"))
               result = operand1 + operand2;
            else if (operator.equals("-"))
               result = operand1 - operand2;
            else if (operator.equals("*"))
               result = operand1 * operand2;
            else if (operator.equals("/"))
               result = operand1 / operand2;
            else
                throw new RuntimeException ("Not Enough Operands");

            s.push(result);
         } // end else // we have an operator

      } // end while (tokenizer.hasNext())

      if (s.isEmpty())
          throw new RuntimeException ("Not Enough Operands");

         result = s.pop();

      if (!s.isEmpty())
          throw new RuntimeException ("Not Enough Operands");

      return result;

   } // end public static int postFixEvaluate(String input)

} // end public class PostFixCalculator

I have this code, a PostFixCalculator but whatever I put in for the while and try, I kept getting an error. The program compiles and runs the way it is posted, but it does not run correctly. I've hit a wall..

like image 703
Paul Lesny Avatar asked Sep 16 '14 20:09

Paul Lesny


People also ask

Why do we use a stack to evaluate postfix expressions?

When evaluating postfix expressions, using a stack to temporarily store operands is necessary because as we are evaluating each character of the postfix expression from left to right, we can't instantly know an operator's right-hand operand.

What is the postfix evaluator?

This Postfix Calculator will evaluate a postfix expression and display the step-by-step process used to complete the evaluation using the stack method. MenuFavs Ad-FreeLOGIN Scroll ToPostfix Evaluator CalcCalcCalculatorCalculatorStepsStepsStepsInstructionsTermsPCalcData? HomeNew? AboutContactSite MapDashboard

What is error 3 in Postfix mail server?

Error 3: Client host [xx.xx.xx.xx] blocked using Spamhaus. In this article, we will look into all the postfix mail server issues and the steps to resolve those issues.

Why does postfix-must issue a STARTTLS command first error?

Sometimes you might have observed "Postfix - Must issue a STARTTLS command first" error in your postfix mail server. It is due to missing smtp_tls_note_starttls_offer parameter in below configuration.


2 Answers

Your while loop is incorrct. Try revisiting it and make correction

like image 168
shiva upadhyay Avatar answered Oct 15 '22 07:10

shiva upadhyay


Just try to do e.printStackTrace() in catch block, and you will see that error is NullPointerException. If you are doing empty catch block you will lose all this information.

try this one:

package test;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class PostFixCalculator {
  public static void main(String[] args) {
    Scanner kbd = new Scanner(System.in);
    String expression;

    System.out.println("Student name, CS-304, Fall 2014, Asst 2c.");

    System.out.println("To quit this program, just hit 'return'.\n");

    System.out.print("Enter a postfix expression: ");
    expression = kbd.nextLine();

    while (!expression.equals("")) {
        try {
            System.out.println(postFixEvaluate(expression));
        } catch (RuntimeException e) {
            System.out.println(e.getLocalizedMessage());
        }

        System.out.print("\nEnter a postfix expression: ");
        expression = kbd.nextLine();

    } // end while (!expression.equals(""))

    System.out.println("\nBye!");
    kbd.close();

  } 

  public static String postFixEvaluate(String input)
  {

  List<String> operatorsAsStrings = getListOfValuesAsString(input.split("\\d+"));
  List<String> digitsAsStrings = getListOfValuesAsString(input.split("\\W+"));


  if(operatorsAsStrings.size() >= digitsAsStrings.size()){
      throw new RuntimeException("Incorrect format of expression.");
  }

  if(digitsAsStrings.size()<2){
      throw new RuntimeException("Not Enough Operands.");
  }

  BigInteger result = new BigInteger("0");
  boolean firstTime = true;

  for (int i=0; i<=digitsAsStrings.size()-1; i++) {

      if(firstTime){
          result = result.add(new BigInteger(digitsAsStrings.get(i)));
          firstTime = false;

      }else{

          String operator = operatorsAsStrings.get(i-1);
          if (operator.equals("+"))
              result = result.add(new BigInteger(digitsAsStrings.get(i)));
          else if (operator.equals("-"))
               result = result.subtract(new BigInteger(digitsAsStrings.get(i)));
          else if (operator.equals("*"))
               result = result.multiply(new BigInteger(digitsAsStrings.get(i)));
          else if (operator.equals("/"))
               result = result.divide(new BigInteger(digitsAsStrings.get(i)));

      }

  }
  return result.toString(); 
 } 

 private static List<String> getListOfValuesAsString(String[] split) {
    List<String> resultList = new ArrayList<>();

    for(String string: split){
        if(string != null && !string.isEmpty()){
            resultList.add(string);
        }
    }

    return resultList;
 }
}
like image 44
LetItRock Avatar answered Oct 15 '22 08:10

LetItRock