加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式&自定义异常 典型案例

发布时间:2020-12-14 01:41:44 所属栏目:百科 来源:网络整理
导读:import java.util.regex.Matcher;import java.util.regex.Pattern;public class Test{public static void main(String[] args){System.out.println(oper(" 12.3+213.1"));}public static float oper(String s){Float res = null;Pattern p = Pattern.compile
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test
{

	public static void main(String[] args)
	{
		System.out.println(oper(" 12.3+213.1"));

	}

	public static float oper(String s)
	{
		Float res = null;
		Pattern p = Pattern
				.compile("s*(d+)(.*)(d+)s*(+|-|*/)s*(d+)(.*)(d+)s*");
		Matcher m = p.matcher(s);

		boolean b = m.matches();
		if (!b)
		{
			throw new couldNotCaculateException("匹配错误");
		}

		String s1 = m.group(1) + m.group(2) + m.group(3);
		String s2 = m.group(5) + m.group(6) + m.group(7);

		Float f1 = Float.parseFloat(s1);
		Float f2 = Float.parseFloat(s2);
		if ("+".equals(m.group(4)))
		{
			res = f1 + f2;
		} else if ("-".equals(m.group(4)))
		{
			res = f1 - f2;
		} else if ("*".equals(m.group(4)))
		{
			res = f1 * f2;
		} else if ("/".equals(m.group(4)))
		{
			if (f2 == 0)
			{
				throw new couldNotCaculateException("除数不能为o");
			}
			res = f1 / f2;
		}

		return res;
	}

}

class couldNotCaculateException extends RuntimeException
{

	private static final long serialVersionUID = -1127307315212919888L;

	public couldNotCaculateException(String msg)
	{
		super(msg);
	}
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读