为什么在一个循环中多次调用该函数? [英] Why is the function being called multiple times in a loop?

查看:90
本文介绍了为什么在一个循环中多次调用该函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用处理开发环境制作了一个图形计算器应用程序,并结合了Java Operation类.然后我在主文件-Calculator.pde中调用了Operation类的实例. 当我在多个实例上有条件地调用该方法时,由于调用该方法的循环和条件,它会多次打印该方法的输出.

I've made a graphical calculator app using the Processing Development Environment and have incorporated a Java Operation class. Then I called instances of the Operation class in my main file - calculator.pde. When I call the method on the multiple instances, conditionally, it prints output from the method multiple times because of the loop and conditional from which the method is called.

这是Operation类的calculate()方法:

String calculate() {
    int operationIndex = userInput.indexOf(operationSymbol);
    ArrayList<String> clickedNumbers = new ArrayList<String>();
    System.out.println(operation + " index: " + operationIndex);
    for (int i = 0; i < operationIndex; i++) {
      clickedNumbers.add(userInput.get(i));         }
    double double1 = calculator.stringToDouble(String.join("", clickedNumbers)); 
    System.out.println("double1: " + double1);
    clickedNumbers.clear();
    int equalsIndex = userInput.indexOf("=");
    for (int i = operationIndex + 1; i < equalsIndex; i++) {
      clickedNumbers.add(userInput.get(i));
    }
    double double2 = calculator.stringToDouble(String.join("", clickedNumbers)); 
    System.out.println("double2: " + double2);
    Double operResult = this.doOperation(double1, double2);
    String operationResult = calculator.doubleToString(operResult);
    System.out.println("Operation Result: " + operationResult);
    return operationResult;
}

所有System.out.println()语句都依赖于方法内部的局部变量.这些是只应打印到控制台一次的内容.每当用户进行操作并按等于时,例如,如果她/她输入15 * 3,它将输出:

All System.out.println() statements depend on local variables inside the method. These are what should be printing out to the console only once. Whenever the user puts in an operation and presses equals, for example, if s/he inputs 15 * 3, it outputs:

上面,控制台输出中突出显示的部分是我想要的输出.

Above, the highlighted part of the console output is my desired output.

这是我的代码,其中调用calculate()方法:

Here is my code where the calculate() method is called:

  String[] numberStr = {"1", "2", "3", "4", "5", "6", "7", "8", "9"};
  Boolean pressedEquals = listName.contains("=");

  for(String number : numberStr) {
  Boolean pressedNumber = listName.contains(number);
    if (pressedNumber && pressedEquals) {
      if (listName.contains("+")) {
        processStatement = "Adding Numbers...";
        result = addition.calculate();
      }
      else if (listName.contains("-")) {
        processStatement = "Subtracting Numbers...";
        result = subtraction.calculate();
      }
      else if (listName.contains("*")) {
        processStatement = "Multiplying Numbers...";
        result = multiplication.calculate();
      }
      else if (listName.contains("/")) {
        processStatement = "Dividing Numbers...";
        result = division.calculate();
      }
      else if (listName.contains("%")) {
        processStatement = "Modulufying Numbers...";
        result = modulus.calculate();
      }
      else if (listName.contains("^")) {
        processStatement = "Expounding numbers...";
        result = exponential.calculate();
      }
    } 
  }


我不明白为什么它打印输出的次数是userInput ArrayList的长度的多少倍.我知道问题是for循环中的pressedNumber布尔值.我知道此问题上的OP遇到了相同的问题,与打印有关根据用户输入时间的长短多次,但是对该问题的答案并不能解释为什么这样做.


I don't understand why it is printing output as many times as the length of the userInput ArrayList. I know the problem is the pressedNumber Boolean in the for loop. I know the OP on this question had the same problem, with it the printing a number of times depending on a length of user input, but the answer to the question did not explain why it was doing this.

解决此问题的一部分是使processStatement成为变量,因为之前我只是在条件内打印了它.这没有用,因为它打印了多次.我无法对方法内的println语句执行此操作,因为它们取决于方法内的变量,并且有很多语句.我的第二个计划是制作一个静态方法printInfo(),但是由于变量的作用域范围太小,所以这也行不通,而且我不能在外部定义它们,因为那样会不准确.

Part of fixing this was making the processStatement into a variable because earlier I just printed it inside the condition. This didn't work because it printed multiple times. I cannot do this for the println statements inside the method because they depend on the variables inside the method, and there are quite a few statements. My second plan was to make a static method printInfo(), but this also wouldn't have worked because of the variables being too tightly scoped, and I can't define them outside because then that would be inaccurate.

这次,我更多地关注堆栈溢出,正则表达式,这些问题添加到我的研究中以解决此问题:

I have looked more on stack overflow, this time for regular expressions, and these questions added to my research to solve this problem:

  • This one for making the regular expression that I am looking for
  • This question for checking if the expression matches the regular expression
  • This question to extract a part of the regEx for later code (my control flow)
  • The answer to this question that makes characters with special meaning be used as regular characters by prepending them with \\

推荐答案

以下是您可能需要在代码中重新考虑的几件事:

Here are a few things that you might want to reconsider in your code:

例如,查看以下代码段:

For example, take a look at this snippet:

String[] numberStr = {"1", "2", "3", "4", "5", "6", "7", "8", "9"};
Boolean pressedEquals = listName.contains("=");

for(String number : numberStr) {
    Boolean pressedNumber = listName.contains(number);
    // ...
}

您在这里不需要此循环.您可以简单地验证listName是否包含数字,运算符,即它是有效的表达式.并且,如果有效,则只需调用calculate()方法.您还可以使用基于正则表达式的验证来强制执行特定的表达式格式.

You don't need this loop here. You can simply validate the listName that it contains digits, operators or not i.e. it is a valid expression. And, then simply call the calculate() method if it is valid. You may also use regex-based validation to enforce your particular expression format.

跳过该循环,然后执行验证,就像这样:

Skipping that loop and after performing validation, it would look like this:

// Validate expression format here
// Example: <number> <operator> <number> <=>
//             1          *        5      =

final boolean isValidated = isValidExpression( /* expression */ );

if ( isValidated == true )
{
    final String op = /* get operator here */;
    switch ( op )
    {
        case "+":
            result = addition.calculate();
            break;

        case "-":
            result = subtraction.calculate();
            break;

       // ... /, *, % ...

        default:
            // ERROR: Invalid operator...
    }
}

除此之外,您还可以使用基于堆栈的表达式求值.

Apart from this, you may use stack-based expression evaluation too.

更新:

以下是使用正则表达式的isValidExpression()方法的示例:

Here's an example of isValidExpression() method with regex:

// Test to validate expression with regex
// Example: <number> <operator> <number> <=>
//             1          *        5      =

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class ExpressionValidator
{
    public static boolean isValidExpression( final String exp )
    {
        final String regex = "\\d+\\s*[*|/|+|-]\\s*\\d+\\s*[=]";
        final Pattern pattern = Pattern.compile( regex );
        final Matcher matcher = pattern.matcher( exp.trim() );
        return matcher.find();
    }

    public static void main( final String[] args )
    {
        final String[] expressions = 
        {  
            " 1 +  2 =",
            " 3 *  5 =",
            "12 + 10 =",
            " 33 = 25 ",
            " +65  65 ",
            "45 666  ="
        };

        for ( final String exp : expressions )
        {
            System.out.println( "[" + exp + "] >> " + isValidExpression( exp ) );
        }
    }
}

输出:

[ 1 +  2 =] >> true
[ 3 *  5 =] >> true
[12 + 10 =] >> true
[ 33 = 25 ] >> false
[ +65  65 ] >> false
[45 666  =] >> false

这是实时示例: https://ideone.com/S9Wf9b

这篇关于为什么在一个循环中多次调用该函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆