【问题标题】:Java geting operators from within a split for function purposeJava 从拆分中获取运算符以实现功能
【发布时间】:2014-10-22 15:15:30
【问题描述】:

好的...我想我可能已经试图简化这段代码了。我将( *, +, /, -) 等运算符放在一个拆分中。知道我想单独打电话给他们在if (operators.equals.(+)){ 中完成他们的透视任务 return num1 + num2. } 那么对于 *, -, / 透视

如何在我之前的代码中正确使用数学:

String function = "[+\\-*/]+"; //this

String[] token = input.split(function);//and this

double num1 = Double.parseDouble(token[0]);

double num2 = Double.parseDouble(token[1]);

double answer;

String operator = input.toCharArray()[token[0].length()]+"";

if (operator.matches(function) && (token[0]+token[1]+operator).length()==input.length()) {

System.out.println("Operation is " + operator+ ", numbers are " + token[0] + " and " + token[1]);
} else {

      System.out.println("Your entry of " + input + " is invalid");
}

【问题讨论】:

  • 抱歉,您的问题是什么?我在解析“在我之前的代码中使用数学时如何正确地做到这一点”时遇到问题?
  • 我并不是要写数学,我的意思是,我怎样才能放置 if 和 if else 语句,以便返回带有两个数字的运算符。示例:num1 is 5 operator is * and num2 is 1, so answer is 5. 如果我的运算符都捆绑在索引中,我该怎么办?
  • 所以您正在尝试构建计算器的解析器部分?很抱歉,但没有(简单的)方法可以映射“如果遇到此符号,请执行此操作”(您称之为“单独调用它们”)。您可以做的是将token 映射到方法名称并使用java 反射来调用该方法。但仅此而已。
  • 另外,我不知道与您的 previous question 有何不同?
  • @mali,我实际上想将功能齐全的编写代码改进为行数更少的代码,因此我决定消除单独调用每个运算符的垃圾,现在我遇到了一个问题确保代码兼容。知道它们是捆绑的,如果选择的运算符是 + 调用返回 num1 + num2,我该怎么做。明白了吗?

标签: java if-statement split match


【解决方案1】:

你没有。

String.split 只返回String 中不匹配的部分。如果你想知道匹配的代码,你需要使用更复杂的正则表达式,即PatternMatcher类,或者自己编写自己的String分词类。

在此示例中,Token 是您自己创建的类):

public List<Token> generateTokenList(String input) {
    List<Token> = new LinkedList<>();

    for(char c : input.toCharArray()) {
        if(Character.isDigit(c)) {
           // handle digit case
        } else if (c == '+') {
           // handle plus
        } else if (c == '-') {
           // handle minus
        } else {
           /* you get the idea */
        }
    }
}

有一些图书馆可以为您执行此操作,例如 ANTLR,但这听起来像是一项学校作业,因此您可能不得不以艰难的方式执行此操作。

【讨论】:

    【解决方案2】:

    将您的 if 正文更改为类似

    if (operator.matches(function) && 
            (token[0] + token[1] + operator).length() == input.length()) 
    {
        double result = 0;
        if (operator.equals("+")) {
            result = num1 + num2;
        } else if (operator.equals("-")) {
            result = num1 - num2;
        } else if (operator.equals("*")) {
            result = num1 * num2;
        } else if (operator.equals("/")) {
            result = num1 / num2;
        }
        System.out.printf("%.2f %s %.2f = %.2f%n", num1, operator, num2,
                result);
    }
    

    您的代码按预期工作。

    【讨论】:

    • 写到重点,但你能告诉我这个 mubojumbo 是什么吗? printf("%.2f %s %.2f = %.2f%n
    • 我建议你阅读Formatter。 “%.2f”是小数点后两位的浮点数,“%s”是String,“%n”是换行符。所以它会打印出类似 "#.## #.## = #.##\n" 的内容,其中 #(s)(和 )被替换为值。
    猜你喜欢
    • 1970-01-01
    • 2020-07-31
    • 2018-06-23
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    • 2011-12-03
    • 1970-01-01
    相关资源
    最近更新 更多