1. if else
观察下面两个遍历数组的程序,分析为什么B不正确
A:
class ArrayTest{
public static void main(String[] args){
int[] arr = new int[]{11,22,33,44,55};
printArray(arr);
}
public static void printArray(int[] arr){
System.out.print("[");
for(int x = 0;x < arr.length;x++){
if(x==arr.length-1){
System.out.println(arr[x]+"]");
}
else{
System.out.print(arr[x]+" ");
}
}
}
}
运行结果:
B:
class ArrayTest{
public static void main(String[] args){
int[] arr = new int[]{11,22,33,44,55};
printArray(arr);
}
public static void printArray(int[] arr){
System.out.print("[");
for(int x = 0;x < arr.length;x++){
if(x==arr.length-1){
System.out.println(arr[x]+"]");
}
System.out.print(arr[x]+" ");
}
}
}
运行结果:
两个程序的区别就在于printArray方法中的for循环里一个是if...else语句,另一个是if语句。如果业务逻辑中事件A和事件B是对立关系(事件A和事件B必有一个且仅有一个发生),则需要使用if..else语句。在遍历数据时,我们想要的是在索引等于arr.length-1时,输出数组的值再加上一个“]"结束遍历,在B中,当x等于arr.length-1时,会执行System.out.println(arr[x]+"]"),执行完成后会继续执行System.out.print(arr[x]+" "),所以不满足业务逻辑(遍历数组)。
2. Math.round()
Math类中提供了三个与取整有关的方法:ceil,floor,round,这些方法的作用于它们的英文名称的含义相对应,例如:ceil的英文意义是天花板,该方法就表示向上取整,Math.ceil(11.3)的结果为12,Math.ceil(-11.6)的结果为-11;floor的英文是地板,该方法就表示向下取整,Math.floor(11.6)的结果是11,Math.floor(-11.4)的结果-12;最难掌握的是round方法,他表示“四舍五入”,算法为Math.floor(x+0.5),即将原来的数字加上0.5后再向下取整,所以,Math.round(11.5)的结果是12,Math.round(-11.5)的结果为-11.