写代码经常犯的错误

1.关于使用BigDecimal进行连续加减

        BigDecimal bigDecimal1 = new BigDecimal(0.02);
        BigDecimal bigDecimal = new BigDecimal("0.02");
        bigDecimal.add(new BigDecimal("2"));
        bigDecimal.add(new BigDecimal("2"));
        System.out.println(bigDecimal1);
        System.out.println(bigDecimal);

执行结果

0.0200000000000000004163336342344337026588618755340576171875
0.02

这告诉我们:
如果需要精确计算浮点数应该使用 BigDecimal来进行计算。
尽量使用构造方法里面传入String类型的参数
使用BigDecimal进行加减乘除的时候返回的值是新的值,不会修改原来的值。
2.idea提示

Reports try finally statements which can use Java 7 Automatic Resource Management. A quickfix is available to convert the try finally statement into a try with resources statement.
This inspection only reports if the project or module is configured to use a language level of 7.0 or higher.

这个的意思是JDK1.7之后java引入了一种新的关闭资源的方法,支持新的 try-with-resources 语句,称为 ARM 块(Automatic Resource Management) ,自动资源管理。它支持的资源必须实现Closeable接口。
修改之前

public static String readFirstLine(String path) {
		if (path != null) {
			File file = new File(path);
			BufferedReader reader = null;
			InputStreamReader bufferedReader = null;
			InputStream inputStream = null;
			String trigger = null;
			try {
				inputStream = new FileInputStream(file);
				bufferedReader = new InputStreamReader(inputStream);
				reader = new BufferedReader(bufferedReader);
				trigger = reader.readLine().trim();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (reader != null) {
						reader.close();
					}
					if (bufferedReader != null) {
						bufferedReader.close();
					}
					if (inputStream != null) {
						inputStream.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return trigger;
		}
		return null;

修改之后

	public static String readFirstLine(String path) {
		if (path != null) {
			File file = new File(path);
			String trigger = null;
			try (InputStream inputStream = new FileInputStream(file);
			InputStreamReader inputStreamReader =new InputStreamReader(inputStream);
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);){
			trigger = bufferedReader.readLine().trim();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return trigger;
		}
		return null;
	}

try语句()里面的资源必须实现Closeble接口。程序会在try执行之后默认去关闭()里面的资源。注意JDK1.7之后才支持的。可以看出来,节省了很多的代码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值