JDK7的try简化写法

今天遇到这样的代码

public static int countWordInFile(String filename, String word) {
       int counter = 0;
       try (FileReader fr = new FileReader(filename)) {
           try (BufferedReader br = new BufferedReader(fr)) {
               String line = null;
               while ((line = br.readLine()) != null) {
                   int index = -1;
                   while (line.length() >= word.length() && (index = line.indexOf(word)) >= 0) {
                       counter++;
                       line = line.substring(index + word.length());
                   }
               }
           }
       } catch (Exception ex) {
           ex.printStackTrace();
       }
       return counter;
   }

这段代码中的try在JDK6及以前的版本中会报try括号后的错,因为没有这种写法。这种写法在JDk7及以后版本可以用。其相当于如下代码

public static int countWordInFile(String filename, String word)
throws IOException {
int counter = 0;
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
try {
try {
String line = null;
while ((line = br.readLine()) != null) {
int index = -1;
while (line.length() >= word.length()
&& (index = line.indexOf(word)) >= 0) {
counter++;
line = line.substring(index + word.length());
}
}
}
catch (Exception ex) {
ex.printStackTrace();
}
return counter;
} finally {
fr.close();
br.close();
}
}

其实就是简化finally,即try后小括号里的代码不再需要在finally代码块中释放。简化了代码书写。

在Python中,`if`语句的简化写法主要有以下几种: 1. **三元运算符**: Python中的三元运算符可以用来在一行中完成简单的条件判断。其语法如下: ```python result = value_if_true if condition else value_if_false ``` 例如: ```python x = 5 y = 10 if x > 0 else 0 print(y) # 输出10 ``` 2. **列表推导式**: 列表推导式可以用来在一行中生成一个新的列表,并且在生成过程中可以包含条件判断。其语法如下: ```python [expression for item in iterable if condition] ``` 例如: ```python numbers = [1, 2, 3, 4, 5] even_numbers = [x for x in numbers if x % 2 == 0] print(even_numbers) # 输出[2, 4] ``` 3. **字典推导式**: 字典推导式可以用来在一行中生成一个新的字典,并且在生成过程中可以包含条件判断。其语法如下: ```python {key_expression: value_expression for item in iterable if condition} ``` 例如: ```python numbers = [1, 2, 3, 4, 5] even_odd_dict = {x: ('even' if x % 2 == 0 else 'odd') for x in numbers} print(even_odd_dict) # 输出{1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd'} ``` 4. **集合推导式**: 集合推导式可以用来在一行中生成一个新的集合,并且在生成过程中可以包含条件判断。其语法如下: ```python {expression for item in iterable if condition} ``` 例如: ```python numbers = [1, 2, 2, 3, 4, 4, 5] even_numbers_set = {x for x in numbers if x % 2 == 0} print(even_numbers_set) # 输出{2, 4} ``` 这些简化写法可以使代码更加简洁和易读,但在使用时需要注意不要过度简化,以免影响代码的可读性和维护性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值