Calculator that can handle any number of numbers and respects order of operation

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
3
down vote

favorite












The next thing I will work on is parentheses. Do you think it would be smarter to split the input into 2 lists, one for operators and one for numbers?



Also, is there anything I can/should improve?



public class T11 

static boolean repeatTry = true;
private static Scanner sInput;
static boolean quit2;
static String repeat;
static boolean repeat2 = true;

/**
* main method. it calls the other methods into action
*/
public static void main(String args)

while (true)

List<String> inputA = getsInputPreFilter();

double solution = calculation(inputA);
System.out.println(solution);




/**
* This method creates an array of inputs for the calculation. Input starts with
* a number, spaces are not required.
*/
public static List<String> getsInputPreFilter() (?<=\d)(?=\D)")));
int arrayLength = inputList.size();
if (inputList.get(0).equals("quit"))
System.exit(0);
else if (arrayLength == 1)
System.out.println(inputList.get(0));


return inputList;


/**
* this calculation calculates any given amount of numbers; it respects the
* order of operation
*/
public static double calculation(List<String> preFilteredList)








share|improve this question



























    up vote
    3
    down vote

    favorite












    The next thing I will work on is parentheses. Do you think it would be smarter to split the input into 2 lists, one for operators and one for numbers?



    Also, is there anything I can/should improve?



    public class T11 

    static boolean repeatTry = true;
    private static Scanner sInput;
    static boolean quit2;
    static String repeat;
    static boolean repeat2 = true;

    /**
    * main method. it calls the other methods into action
    */
    public static void main(String args)

    while (true)

    List<String> inputA = getsInputPreFilter();

    double solution = calculation(inputA);
    System.out.println(solution);




    /**
    * This method creates an array of inputs for the calculation. Input starts with
    * a number, spaces are not required.
    */
    public static List<String> getsInputPreFilter() (?<=\d)(?=\D)")));
    int arrayLength = inputList.size();
    if (inputList.get(0).equals("quit"))
    System.exit(0);
    else if (arrayLength == 1)
    System.out.println(inputList.get(0));


    return inputList;


    /**
    * this calculation calculates any given amount of numbers; it respects the
    * order of operation
    */
    public static double calculation(List<String> preFilteredList)








    share|improve this question























      up vote
      3
      down vote

      favorite









      up vote
      3
      down vote

      favorite











      The next thing I will work on is parentheses. Do you think it would be smarter to split the input into 2 lists, one for operators and one for numbers?



      Also, is there anything I can/should improve?



      public class T11 

      static boolean repeatTry = true;
      private static Scanner sInput;
      static boolean quit2;
      static String repeat;
      static boolean repeat2 = true;

      /**
      * main method. it calls the other methods into action
      */
      public static void main(String args)

      while (true)

      List<String> inputA = getsInputPreFilter();

      double solution = calculation(inputA);
      System.out.println(solution);




      /**
      * This method creates an array of inputs for the calculation. Input starts with
      * a number, spaces are not required.
      */
      public static List<String> getsInputPreFilter() (?<=\d)(?=\D)")));
      int arrayLength = inputList.size();
      if (inputList.get(0).equals("quit"))
      System.exit(0);
      else if (arrayLength == 1)
      System.out.println(inputList.get(0));


      return inputList;


      /**
      * this calculation calculates any given amount of numbers; it respects the
      * order of operation
      */
      public static double calculation(List<String> preFilteredList)








      share|improve this question













      The next thing I will work on is parentheses. Do you think it would be smarter to split the input into 2 lists, one for operators and one for numbers?



      Also, is there anything I can/should improve?



      public class T11 

      static boolean repeatTry = true;
      private static Scanner sInput;
      static boolean quit2;
      static String repeat;
      static boolean repeat2 = true;

      /**
      * main method. it calls the other methods into action
      */
      public static void main(String args)

      while (true)

      List<String> inputA = getsInputPreFilter();

      double solution = calculation(inputA);
      System.out.println(solution);




      /**
      * This method creates an array of inputs for the calculation. Input starts with
      * a number, spaces are not required.
      */
      public static List<String> getsInputPreFilter() (?<=\d)(?=\D)")));
      int arrayLength = inputList.size();
      if (inputList.get(0).equals("quit"))
      System.exit(0);
      else if (arrayLength == 1)
      System.out.println(inputList.get(0));


      return inputList;


      /**
      * this calculation calculates any given amount of numbers; it respects the
      * order of operation
      */
      public static double calculation(List<String> preFilteredList)










      share|improve this question












      share|improve this question




      share|improve this question








      edited Jun 10 at 20:13









      Jamal♦

      30.1k11114225




      30.1k11114225









      asked Jun 8 at 11:07









      Maritn Ge

      183




      183




















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          1. There is no graceful way to end the program. the program should accept some input like "quit" and exit gracefully.


          2. regarding "-" as minus: you should take care to support when user specifies a negative number. this is also true for "+" (user may wish to explicitly specify positive number)


          3. your calculation doesn't seem to take precedence into account. you know, multiplication and division before adding/substraction. and suport for parenthesis will make this even harder. You should consider converting the input infix format to postfix. this is also known as reverse polish notation and its biggest advantage is that it does not need parenthesis to specify precedence.



          4. The specification of the operators as string values is problematic for two reasons: 1) you do not detect typo and 2) if you want to support more operators (like '%' or '^' (power of)) you need to remember to make changes in several places the code. a solution for 1) is to use enum:



             public enum Operator 
            PLUS("+"),
            MINUS("-"),
            MULTIPLE("*"),
            DIVIDE("/");

            private String symbol;

            Operator(String symbol)
            this.symbol = symbol;


            // throws IllegalArgumentException for unrecognized input
            public static Operator fromSymbol(String symbol)
            return Arrays.stream(Operator.values())
            .filter(op -> op.symbol.equals(symbol))
            .findFirst().orElseThrow(IllegalArgumentException::new);




          then you can replace the String comparison with



           if (Operator.fromSymbol(preFilteredList.get(operatorIndex)) == Operator.MINUS) {


          a solution for 2) is to have a separate class+method for each operator with a common interface. it so happens that Java already have a functional interface for a binary operator:



           public enum Operator 
          PLUS("+", ((num1, num2) -> num1 + num2)),
          MINUS("-", ((num1, num2) -> num1 - num2)),
          MULTIPLE("*")..., // same principal
          DIVIDE("/")...;

          private String symbol;
          private BinaryOperator<Double> mathOperator;

          Operator(String symbol, BinaryOperator<Double> mathOperator)
          ...


          public double apply (double num1, double num2)
          return mathOperator.apply(num1, num2);




          and there you have it: the enum and its implementation in one line. Adding new operatos is quite easy (and safe) with this construct






          share|improve this answer























          • it does take it into account, by first calculating * IF any exist, ELSE it goes to /,then to + and -. The problem tho is, that (6/7)*5 isnt 6/(7*5). At the moment it first calculates the second one (6/35) while the answer should be (30/7)
            – Maritn Ge
            Jun 11 at 9:25











          Your Answer




          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: false,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );








           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f196108%2fcalculator-that-can-handle-any-number-of-numbers-and-respects-order-of-operation%23new-answer', 'question_page');

          );

          Post as a guest






























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          1
          down vote



          accepted










          1. There is no graceful way to end the program. the program should accept some input like "quit" and exit gracefully.


          2. regarding "-" as minus: you should take care to support when user specifies a negative number. this is also true for "+" (user may wish to explicitly specify positive number)


          3. your calculation doesn't seem to take precedence into account. you know, multiplication and division before adding/substraction. and suport for parenthesis will make this even harder. You should consider converting the input infix format to postfix. this is also known as reverse polish notation and its biggest advantage is that it does not need parenthesis to specify precedence.



          4. The specification of the operators as string values is problematic for two reasons: 1) you do not detect typo and 2) if you want to support more operators (like '%' or '^' (power of)) you need to remember to make changes in several places the code. a solution for 1) is to use enum:



             public enum Operator 
            PLUS("+"),
            MINUS("-"),
            MULTIPLE("*"),
            DIVIDE("/");

            private String symbol;

            Operator(String symbol)
            this.symbol = symbol;


            // throws IllegalArgumentException for unrecognized input
            public static Operator fromSymbol(String symbol)
            return Arrays.stream(Operator.values())
            .filter(op -> op.symbol.equals(symbol))
            .findFirst().orElseThrow(IllegalArgumentException::new);




          then you can replace the String comparison with



           if (Operator.fromSymbol(preFilteredList.get(operatorIndex)) == Operator.MINUS) {


          a solution for 2) is to have a separate class+method for each operator with a common interface. it so happens that Java already have a functional interface for a binary operator:



           public enum Operator 
          PLUS("+", ((num1, num2) -> num1 + num2)),
          MINUS("-", ((num1, num2) -> num1 - num2)),
          MULTIPLE("*")..., // same principal
          DIVIDE("/")...;

          private String symbol;
          private BinaryOperator<Double> mathOperator;

          Operator(String symbol, BinaryOperator<Double> mathOperator)
          ...


          public double apply (double num1, double num2)
          return mathOperator.apply(num1, num2);




          and there you have it: the enum and its implementation in one line. Adding new operatos is quite easy (and safe) with this construct






          share|improve this answer























          • it does take it into account, by first calculating * IF any exist, ELSE it goes to /,then to + and -. The problem tho is, that (6/7)*5 isnt 6/(7*5). At the moment it first calculates the second one (6/35) while the answer should be (30/7)
            – Maritn Ge
            Jun 11 at 9:25















          up vote
          1
          down vote



          accepted










          1. There is no graceful way to end the program. the program should accept some input like "quit" and exit gracefully.


          2. regarding "-" as minus: you should take care to support when user specifies a negative number. this is also true for "+" (user may wish to explicitly specify positive number)


          3. your calculation doesn't seem to take precedence into account. you know, multiplication and division before adding/substraction. and suport for parenthesis will make this even harder. You should consider converting the input infix format to postfix. this is also known as reverse polish notation and its biggest advantage is that it does not need parenthesis to specify precedence.



          4. The specification of the operators as string values is problematic for two reasons: 1) you do not detect typo and 2) if you want to support more operators (like '%' or '^' (power of)) you need to remember to make changes in several places the code. a solution for 1) is to use enum:



             public enum Operator 
            PLUS("+"),
            MINUS("-"),
            MULTIPLE("*"),
            DIVIDE("/");

            private String symbol;

            Operator(String symbol)
            this.symbol = symbol;


            // throws IllegalArgumentException for unrecognized input
            public static Operator fromSymbol(String symbol)
            return Arrays.stream(Operator.values())
            .filter(op -> op.symbol.equals(symbol))
            .findFirst().orElseThrow(IllegalArgumentException::new);




          then you can replace the String comparison with



           if (Operator.fromSymbol(preFilteredList.get(operatorIndex)) == Operator.MINUS) {


          a solution for 2) is to have a separate class+method for each operator with a common interface. it so happens that Java already have a functional interface for a binary operator:



           public enum Operator 
          PLUS("+", ((num1, num2) -> num1 + num2)),
          MINUS("-", ((num1, num2) -> num1 - num2)),
          MULTIPLE("*")..., // same principal
          DIVIDE("/")...;

          private String symbol;
          private BinaryOperator<Double> mathOperator;

          Operator(String symbol, BinaryOperator<Double> mathOperator)
          ...


          public double apply (double num1, double num2)
          return mathOperator.apply(num1, num2);




          and there you have it: the enum and its implementation in one line. Adding new operatos is quite easy (and safe) with this construct






          share|improve this answer























          • it does take it into account, by first calculating * IF any exist, ELSE it goes to /,then to + and -. The problem tho is, that (6/7)*5 isnt 6/(7*5). At the moment it first calculates the second one (6/35) while the answer should be (30/7)
            – Maritn Ge
            Jun 11 at 9:25













          up vote
          1
          down vote



          accepted







          up vote
          1
          down vote



          accepted






          1. There is no graceful way to end the program. the program should accept some input like "quit" and exit gracefully.


          2. regarding "-" as minus: you should take care to support when user specifies a negative number. this is also true for "+" (user may wish to explicitly specify positive number)


          3. your calculation doesn't seem to take precedence into account. you know, multiplication and division before adding/substraction. and suport for parenthesis will make this even harder. You should consider converting the input infix format to postfix. this is also known as reverse polish notation and its biggest advantage is that it does not need parenthesis to specify precedence.



          4. The specification of the operators as string values is problematic for two reasons: 1) you do not detect typo and 2) if you want to support more operators (like '%' or '^' (power of)) you need to remember to make changes in several places the code. a solution for 1) is to use enum:



             public enum Operator 
            PLUS("+"),
            MINUS("-"),
            MULTIPLE("*"),
            DIVIDE("/");

            private String symbol;

            Operator(String symbol)
            this.symbol = symbol;


            // throws IllegalArgumentException for unrecognized input
            public static Operator fromSymbol(String symbol)
            return Arrays.stream(Operator.values())
            .filter(op -> op.symbol.equals(symbol))
            .findFirst().orElseThrow(IllegalArgumentException::new);




          then you can replace the String comparison with



           if (Operator.fromSymbol(preFilteredList.get(operatorIndex)) == Operator.MINUS) {


          a solution for 2) is to have a separate class+method for each operator with a common interface. it so happens that Java already have a functional interface for a binary operator:



           public enum Operator 
          PLUS("+", ((num1, num2) -> num1 + num2)),
          MINUS("-", ((num1, num2) -> num1 - num2)),
          MULTIPLE("*")..., // same principal
          DIVIDE("/")...;

          private String symbol;
          private BinaryOperator<Double> mathOperator;

          Operator(String symbol, BinaryOperator<Double> mathOperator)
          ...


          public double apply (double num1, double num2)
          return mathOperator.apply(num1, num2);




          and there you have it: the enum and its implementation in one line. Adding new operatos is quite easy (and safe) with this construct






          share|improve this answer















          1. There is no graceful way to end the program. the program should accept some input like "quit" and exit gracefully.


          2. regarding "-" as minus: you should take care to support when user specifies a negative number. this is also true for "+" (user may wish to explicitly specify positive number)


          3. your calculation doesn't seem to take precedence into account. you know, multiplication and division before adding/substraction. and suport for parenthesis will make this even harder. You should consider converting the input infix format to postfix. this is also known as reverse polish notation and its biggest advantage is that it does not need parenthesis to specify precedence.



          4. The specification of the operators as string values is problematic for two reasons: 1) you do not detect typo and 2) if you want to support more operators (like '%' or '^' (power of)) you need to remember to make changes in several places the code. a solution for 1) is to use enum:



             public enum Operator 
            PLUS("+"),
            MINUS("-"),
            MULTIPLE("*"),
            DIVIDE("/");

            private String symbol;

            Operator(String symbol)
            this.symbol = symbol;


            // throws IllegalArgumentException for unrecognized input
            public static Operator fromSymbol(String symbol)
            return Arrays.stream(Operator.values())
            .filter(op -> op.symbol.equals(symbol))
            .findFirst().orElseThrow(IllegalArgumentException::new);




          then you can replace the String comparison with



           if (Operator.fromSymbol(preFilteredList.get(operatorIndex)) == Operator.MINUS) {


          a solution for 2) is to have a separate class+method for each operator with a common interface. it so happens that Java already have a functional interface for a binary operator:



           public enum Operator 
          PLUS("+", ((num1, num2) -> num1 + num2)),
          MINUS("-", ((num1, num2) -> num1 - num2)),
          MULTIPLE("*")..., // same principal
          DIVIDE("/")...;

          private String symbol;
          private BinaryOperator<Double> mathOperator;

          Operator(String symbol, BinaryOperator<Double> mathOperator)
          ...


          public double apply (double num1, double num2)
          return mathOperator.apply(num1, num2);




          and there you have it: the enum and its implementation in one line. Adding new operatos is quite easy (and safe) with this construct







          share|improve this answer















          share|improve this answer



          share|improve this answer








          edited Jun 10 at 7:41


























          answered Jun 10 at 7:31









          Sharon Ben Asher

          2,038512




          2,038512











          • it does take it into account, by first calculating * IF any exist, ELSE it goes to /,then to + and -. The problem tho is, that (6/7)*5 isnt 6/(7*5). At the moment it first calculates the second one (6/35) while the answer should be (30/7)
            – Maritn Ge
            Jun 11 at 9:25

















          • it does take it into account, by first calculating * IF any exist, ELSE it goes to /,then to + and -. The problem tho is, that (6/7)*5 isnt 6/(7*5). At the moment it first calculates the second one (6/35) while the answer should be (30/7)
            – Maritn Ge
            Jun 11 at 9:25
















          it does take it into account, by first calculating * IF any exist, ELSE it goes to /,then to + and -. The problem tho is, that (6/7)*5 isnt 6/(7*5). At the moment it first calculates the second one (6/35) while the answer should be (30/7)
          – Maritn Ge
          Jun 11 at 9:25





          it does take it into account, by first calculating * IF any exist, ELSE it goes to /,then to + and -. The problem tho is, that (6/7)*5 isnt 6/(7*5). At the moment it first calculates the second one (6/35) while the answer should be (30/7)
          – Maritn Ge
          Jun 11 at 9:25













           

          draft saved


          draft discarded


























           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f196108%2fcalculator-that-can-handle-any-number-of-numbers-and-respects-order-of-operation%23new-answer', 'question_page');

          );

          Post as a guest













































































          Popular posts from this blog

          Chat program with C++ and SFML

          Function to Return a JSON Like Objects Using VBA Collections and Arrays

          Will my employers contract hold up in court?