1.判断奇数
错误代码:
package pitfall;
public class NO1 {
public static boolean isOdd(int i){
return i%2==1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(NO1.isOdd(-1));
}
}
正确代码:
package pitfall;
public class NO1 {
public static boolean isOdd(int i){
return i % 2 != 0;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(NO1.isOdd(-1));
}
}
错误原因:没有把负数的奇数考虑进去.
2.浮点数相减
package pitfall;
import java.math.BigDecimal;
public class NO1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(2.0-1.1);
BigDecimal num1=new BigDecimal("2.0");
BigDecimalnum2=new BigDecimal("1.1");
System.out.println(num1.subtract(num2));
System.out.printf("%.1f",2.0-1.1);
}
}
结果
0.8999999999999999
0.9
0.9
直接相减,产生错误结果,解决方法用BigDecimal减。注意实例化的时候要用字符串参数实例化,不然也是会出现同样的错误,或者用printf也可以解决.
3.long的运算
package pitfall;
public class NO1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
final long MICROS_PER_DAY=24*60*60*1000*1000;
System.out.println(MICROS_PER_DAY);
}
}
发现结果不对,500654080
原因是等式右边是整型数在运算,这么大的数据溢出了,解决方法是
final long MICROS_PER_DAY=24L*60*60*1000*1000;
int和long相乘这样类型会提升为long了。就可以得到正确的答案。
4.finally不一定会执行.
例如:
package no14;
public class GoodBye {
public static void main(String[] args) {
try {
System.out.println("Hello world");
System.exit(0);
} finally {
System.out.println("Goodbye world");
}
}
}
结果输出:
Hello world
5.错误的关闭方法
package pitfall;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class NO1 {
public static void main(String[] args) {
}
public static void copy(String src, String dest) throws IOException {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(src);
out = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int n;
while ((n = in.read(buf)) > 0)
out.write(buf, 0, n);
} finally {
if (in != null) in.close();
if (out != null) out.close();
}
}
}
finally中可能抛出异常,看比较严谨的代码如下:
package pitfall;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class NO1 {
public static void main(String[] args) {
}
public static void copy(String src, String dest) throws IOException {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(src);
out = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int n;
while ((n = in.read(buf)) > 0)
out.write(buf, 0, n);
} finally {
if (in != null) try{in.close(); }
catch(IOException e){
e.printStackTrace();
}finally{
in=null;
}
if (out != null) try{out.close();}
catch(IOException e){
e.printStackTrace();
}
finally{
out=null;
}
}
}
}