java - 是否可以在运算符之前和之后剪切字符串?

标签 java

我正在 GUI 上开发我的第一个计算器项目,我获取输入并使用 Action Listner 将其连接到字符串字段中。

calculation = calculation + " 4 ";
calculation = calculation + " * ";
calculation = calculation + " 9 ";

使用子字符串取出第一个数字和第二个数字,将它们转换并放入两个字段中

num1 = Integer.parseInt(calculation.substring(0, 1));
num2 = Integer.parseInt(calculation.substring(4, 5));

enter image description here

问题是我不能在运算符之前使用超过 x 位数字、在运算符之后使用超过 y 位数字的子字符串。 我可以使用 subString 内置方法来做到这一点吗?如果我不能,我怎样才能使用其他方法来做到这一点?

enter image description here

最佳答案

您可以使用String.splitString.contains:

    String equation = "4+ 10";
    equation.replaceAll(" ", "");//get rid if the space

    String[] buffer = null;
    if (equation.contains("+"))
        buffer = equation.split("\\+");
    else if (equation.contains("*"))
        buffer = equation.split("\\*");
    else if (equation.contains("/"))
        buffer = equation.split("\\/");
    else if (equation.contains("-"))
        buffer = equation.split("\\-");


    if(buffer != null && buffer.length == 2)
    {
        int term1 = Integer.parseInt(buffer[0]);
        int term2 = Integer.parseInt(buffer[1]);

        //call you calculation  ode

    }else
        System.out.println("Fail to parse equation");

或者按照 Vince Emigh 的建议使用单个正则表达式:

    String equation = "4+ 10";
    equation.replaceAll(" ", "");//get rid if the space

    final String [] buffer = equation.split("\\+|\\*|\\-|\\/");


    if(buffer.length == 2)
    {
        int term1 = Integer.parseInt(buffer[0]);
        int term2 = Integer.parseInt(buffer[1]);

        //call you calculation  ode

    }else
        System.out.println("Fail to parse equation");

关于java - 是否可以在运算符之前和之后剪切字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26658861/

相关文章:

java - 如何强制我的数组为特定长度 - Java

java - 如何使用 Spring Boot 配置嵌入式 ActiveMQ Broker URL

java - 使用构造函数创建新对象

java - JScrollPane 不会显示在 JTextArea 中

java - 列表迭代器导致堆分配?

java - 如何从 Android 中的 MainActivity 调用静态方法中的内容

java - Java HashSet<Long> 应该占用多少内存

java - Hadoop - 类型不匹配 : cannot convert from List<Text> to List<String>

java - 获取数组第二维的长度

java - 如何将 eclipse 中的 scala 项目中的文件包含到 netbeans 中的 java 项目中