给你一个字符串
如果字符串是符合运算规则(数字+“+,-”)的运算式就计算出结果,否则就返回正在搜索中。
运算规则只判断“+,-”,比如:输入:02+9 搜索中
输入:ssss 搜索中
输入: a+9 搜索中
输入:9+9 返回 19
输入:989+9-909 返回 89

解决方案 »

  1.   


    package com.ricky.www;import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import java.util.Scanner;public class Test{
    public static void main(String[] args){
    String regex = "^(\\d+)\\s*([-+])\\s*(\\d+)$";
    String format = "9 + 9";
    System.out.println("input a math expression like :" + format + " and then carriage return.");
    Scanner input = new Scanner(System.in);
    String expression = input.nextLine(); Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(expression);

    String result = "正在查询中";
    if(matcher.find()){
    int num1 = Integer.parseInt(matcher.group(1));
    String operator = matcher.group(2);
    int num2 = Integer.parseInt(matcher.group(3)); if(operator.equals("+")){
    result = num1 + num2 + "";
    }else{
    result = num1 - num2 + "";
    }
    }
    System.out.println(expression + " = " + result);
    }
    }用正则做
      

  2.   


    String regex = "^(\\d+)\\s*([-+])\\s*(\\d+)$";最好把这句改成 String regex = "^(\\d+)\\s*([-+])\\s*(\\d+)\\s*$";