【问题标题】:From String to Integer Functions从字符串到整数函数
【发布时间】:2017-02-05 03:30:12
【问题描述】:

我正在尝试编写一个程序,它将接收作为字符串的函数并解决它。例如。 "5*5+2/2-8+5*5-2" 应该返回 41

我为乘法和除法编写了代码,它运行良好:

  public class Solver 
{
    public static void operationS(String m) 
    {
        ArrayList<String> z = new ArrayList<String>();
        char e= ' ';
        String x= " ";
        for (int i =0; i<m.length();i++)
        {
            e= m.charAt(i);
            x= Character.toString(e);


            z.add(x);
        }
         for (int i =0; i<z.size();i++)
            {
                System.out.print(z.get(i));
            }

        other(z);
    }

    public static void other(ArrayList<String> j)
    {
        int n1=0;
        int n2=0;
        int f=0;
        String n= " ";
          for (int m=0; m<j.size();m++)
          {

              if ((j.get(m)).equals("*"))
              {
                 n1 = Integer.parseInt(j.get(m-1));
                 n2 = Integer.parseInt(j.get(m+1));
                 f= n1*n2;
                 n = Integer.toString(f);

                 j.set(m,n);
                 j.remove(m+1);
                 j.remove(m-1);

                 m=0;
              }

              for (int e=0; e<j.size();e++)
              {

                  if ((j.get(e)).equals("/"))
                  {
                     n1 = Integer.parseInt(j.get(e-1));
                     n2 = Integer.parseInt(j.get(e+1));
                     f= n1/n2;
                     n = Integer.toString(f);

                     j.set(e,n);
                     j.remove(e+1);
                     j.remove(e-1);

                     e=0;
                  }

              }   
    }

          System.out.println();
          for (int i1 =0; i1<j.size();i1++)
            {
                System.out.print(j.get(i1)+",");
            }

但是,对于加减法,由于加减法没有先后顺序,所以我写了如下:

  int x1=0;
          int x2=0;
          int x3=0;
          String z = " ";

          for (int g=0; g<j.size();g++)
          {
              if ((j.get(g)).equals("+"))
              {
                  x1= Integer.parseInt(j.get(g-1));
                  x2= Integer.parseInt(j.get(g+1));
                  x3= x1+x2;
                  z = Integer.toString(x3);

                  j.set(g,z);
                  j.remove(g+1);
                  j.remove(g-1);

                  g=0;
              }
             g=0;

              if ((j.get(g)).equals("-"))
              {
                  x1= Integer.parseInt(j.get(g-1));
                  x2= Integer.parseInt(j.get(g+1));
                  x3= x1-x2;
                  z = Integer.toString(x3);

                  j.set(g,z);
                  j.remove(g+1);
                  j.remove(g-1);

                  g=0;
              }

              g=0;
          }

          System.out.println();
          for (int i1 =0; i1<j.size();i1++)
            {
                System.out.print(j.get(i1)+",");
            }

在此之后,它会打印:

25,+,1,-,8,+,25,–,2,

。我究竟做错了什么?乘法和除法似乎工作得很好

【问题讨论】:

标签: java string function methods integer


【解决方案1】:

你有两个问题:

1) if 和 else 块之后的 g=0; 语句会使您进入无限循环。

2) 从您给出的输出中,第一个减号 (-) 是 Unicode 字符 HYPHEN-MINUS (U+002D),而第二个减号 (-) 是 Unicode 字符 EN DASH (U+2013),所以 (j.get(g)).equals("-") 对第二个减号失败,因为它们是不相等。

【讨论】:

  • 这就是好东西。总会有人发现“直接”的问题。
  • 我似乎不明白数字 2。如何在我的代码中解决这个问题?抱歉,谢谢
  • 这不是关于代码,而是关于输入。第二个减号不是减号,是破折号,是不同的字符。
  • 哦,好的,谢谢!但为什么“+”也不起作用? @uoyilmaz
  • 我试了一下,去掉多余的g=0;后输出为“43,–,2”在 if 块之外。所以“+”有效。
【解决方案2】:

寻求一个对您的具体问题没有帮助的答案,但希望对您的帮助远不止于此。

乍一看,您的代码存在各种问题:

  1. 您到处都在使用超短变量名。这可能会为您节省 1 分钟的打字时间;每次阅读代码都会花费您 5、10、x 分钟;或展示给其他人。所以:不要那样做。使用能够说明该名称背后的内容的名称。
  2. 您正在使用大量低级代码。例如,您使用“couting-for”循环来迭代列表(称为 j,这真的很可怕!)。意思是:你让你的代码比它应该的要复杂得多。
  3. 这样看来,到目前为止似乎没有人告诉你,但代码的理念是:它应该易于阅读和理解。可能你没有为此获得分数,但相信我:从长远来看,学习编写可读代码是一项非常重要的技能。如果这让您感到好奇,请看看您是否可以了解 Robert Martin 的“清洁代码”。并研究那本书。然后再研究一下。再说一遍。

但真正的问题是你解决这个问题的方法。正如我所假设的:这是学习任务的一部分。下一步将是你没有简单的表达式,如“1+2*3”;但是你被要求处理诸如“sqrt(2) + 3”之类的东西。然后你会被要求添加变量等。然后你的整个方法就会崩溃。因为你简单的字符串操作不会再这样做了。

从这个意义上说:您应该查看question,并仔细研究 Boann 的第二个答案,以了解如何创建一个 解析器,将您的输入字符串分解为 表达式 然后进行评估。您的代码“一起”做这两件事;因此,增强所提供的功能变得非常困难。

【讨论】:

  • 你在for循环中设置g=0,我认为这将是一个无限循环。
  • @Whatzs 我猜你想将你的评论“移动”到这个问题上。我认为您在这里与错误的人“交谈” ;-)
  • 因为我希望它从头开始检查@Whatzs
  • @ZeldaX 不,问题是你编写的代码你不明白它在做什么。这是最重要的。
【解决方案3】:

您可以使用内置的Javascript引擎

public static void main(String[] args) throws Exception{
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");
    String code = "5*5+2/2-8+5*5-2";
    System.out.println(engine.eval(code));
}

【讨论】:

  • 这是一个作业,我需要像我在问题中显示的那样写它。谢谢@tionio
【解决方案4】:

主要是不要重复自己(DRY 原则)。并使用抽象(全名,合理时提取方法)。当使用多个方法时,静态方法有点麻烦。在这里使用单独的方法很方便。

也许你想要类似的东西:

Solver solver = new Solver();
List<String> expr = solver.expression("5*5+2/2-8+5*5-2");
String result = solver.solve(expr);

一个更抽象的 Solver 类会做:

class Solver {

    List<String> expression(String expr) {
        String[] args = expr.split("\\b");
        List<String> result = new ArrayList<>();
        Collections.addAll(result, args);
        return result;
    }

    String solve(List<String> args) {
        solveBinaryOps(args, "[*/]");
        solveBinaryOps(args, "[-+]");
        return args.stream().collect(Collectors.joining(""));
    }

上面的solveBinaryOps 接收正则表达式模式,或者只是以某种形式接收您想要处理的运算符。 它负责运算符的优先级。

    private void solveBinaryOps(List<String> args, String opPattern) {
        for (int i = 1; i + 1 < args.length; ++i) {
            if (args.get(i).matches(opPattern)) {
                String value = evalBinaryOp(args.get(i - 1), args.get(i), args.get(i + 1));
                args.set(i, value);
                args.remove(i + 1);
                args.remove(i - 1);
                --i; // Continue from here.
            }
        }
    }

    private String evalBinaryOp(String lhs, String op, String rhs) {
        int x = Integer.parseInt(lhs);
        int y = Integer.parseInt(rhs);
        int z = 0;
        switch (op) {
        case "*":
            z = x * y;
            break;
        case "/":
            z = x / y;
            break;
        case "+":
            z = x + y;
            break;
        case "-":
            z = x - y;
            break;
        }
        return Integer.toString(z);
     }
}

以上几点可以改进。但它是可读的,可重写的。

【讨论】:

    【解决方案5】:
    public class Solver {
    public static void main(String args[]) {
        operation("5+2*5-6/2+1+5*12/3");
    }
    
    public static void operation(String m) {
        ArrayList<Object> expressions = new ArrayList<Object>();
        String e;
        String x = "";
        for (int i = 0; i < m.length(); i++) {
            e = m.substring(i, i + 1);
            if (!(e.equals("*") || e.equals("/") || e.equals("+") || e
                    .equals("-"))) {
                x += e;
                continue;
            } else {
                if (!x.equals("") && x.matches("[0-9]+")) {
                    int oper = Integer.parseInt(x);
                    expressions.add(oper);
                    expressions.add(m.charAt(i));
                    x = "";
                }
            }
        }
        if (!x.equals("") && x.matches("[0-9]+")) {
            int oper = Integer.parseInt(x);
            expressions.add(oper);
            x = "";
        }
        for (int i = 0; i < expressions.size(); i++) {
            System.out.println(expressions.get(i));
        }
        evaluateExpression(expressions);
    }
    
    public static void evaluateExpression(ArrayList<Object> exp) {
        //Considering priorities we calculate * and / first and put them in a list mulDivList
        ArrayList<Object> mulDivList=new ArrayList<Object>();
        for (int i = 0; i < exp.size(); i++) {
            if (exp.get(i) instanceof Character) {
                if ((exp.get(i)).equals('*')) {
                    int tempRes = (int) exp.get(i - 1) * (int) exp.get(i + 1);
                    exp.set(i - 1, null);
                    exp.set(i, null);
                    exp.set(i + 1, tempRes);
                }
                else if ((exp.get(i)).equals('/')) {
                    int tempRes = (int) exp.get(i - 1) / (int) exp.get(i + 1);
                    exp.set(i - 1, null);
                    exp.set(i, null);
                    exp.set(i + 1, tempRes);
                }
            }
        }
        //Create new list with only + and - operations
    
        for(int i=0;i<exp.size();i++)
        {
            if(exp.get(i)!=null)
                mulDivList.add(exp.get(i));
        }
        //Calculate + and - .
        for(int i=0;i<mulDivList.size();i++)
        {
             if ((mulDivList.get(i)).equals('+')) {
                int tempRes = (int) mulDivList.get(i - 1) + (int) mulDivList.get(i + 1);
                mulDivList.set(i - 1, null);
                mulDivList.set(i, null);
                mulDivList.set(i + 1, tempRes);
            }
            else if ((mulDivList.get(i)).equals('-')) {
                int tempRes = (int) mulDivList.get(i - 1) - (int) mulDivList.get(i + 1);
                mulDivList.set(i - 1, null);
                mulDivList.set(i, null);
                mulDivList.set(i + 1, tempRes);
            }
        }
        System.out.println("Result is : " + mulDivList.get(mulDivList.size() - 1));
    
    }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-04-07
      • 2016-04-30
      • 2014-01-26
      • 2018-08-18
      • 2011-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      相关资源
      最近更新 更多