练习
1.编写一个Utils类,定义一个getMax方法,接收一个double数组,求最大值并返回结果
传入的double数组成员个数为0,如何处理(异常、包装类、自定义类)
传入的double数组是null,如何处理(异常、包装类、自定义类)
public class Hello {
public static void main(String[] args) throws Exception {
// // 异常处理
// double[] a=new double[]{};
// double max = Utils.getMax(a);
// System.out.println(max);
// 包装类
double[] a = new double[]{};
Double max = Utils.getMax(a);
if (max == null) {
System.out.println("数组成员数不能为0");
} else {
System.out.println(max);
}
}
}
public class Utils {
// // 异常处理
// static double getMax(double[] a) throws Exception {
// if (a.length==0){
// throw new Exception("数组成员不能为0");
// }
// double max=a[0];
// for (int i = 0; i < a.length; i++) {
// if (max<a[i]){
// max=a[i];
// }
// }
// return max;
// }
// 包装类
static Double getMax(double[] a) throws Exception {
if (a.length==0){
return null;
}
double max=a[0];
for (int i = 0; i < a.length; i++) {
if (max<a[i]){
max=a[i];
}
}
return max;
}
}
2.定义一个find方法,实现对字符串数组中的元素查找,并返回索引,找不到返回 -1
public class Hello {
public static void main(String[] args) throws Exception {
String[] a = new String[]{"czw", "lbw", "qnzw", "python", "nb"};
String b = "czw";
System.out.println(find(a, b));
}
static int find(String[] a, String b) {
for (int i = 0; i < a.length; i++) {
// 引用类型的比较一般使用 equals
if (a[i].equals(b)) {
return i;
}
}
return -1;
}
}
3.定义圆类Circle,定义属性半径radius,提供显示圆周长的方法,显示圆面积的方法 Math.PI
public class Circle {
double radius = 0;
double zhouchang() {
return 2 * Math.PI * radius;
}
double mianji() {
return Math.PI * radius * radius;
}
}
public class Hello {
public static void main(String[] args) throws Exception {
Circle circle = new Circle();
circle.radius = 10;
System.out.println(circle.zhouchang());
System.out.println(circle.mianji());
}
}
4.以下代码输出结果为?
public class Hello {
int count = 100;
public void count1() {
count = 200;
System.out.println("count1 = " + count); // 200
}
public void count2() {
System.out.println("count2 = " + count++);
}
public static void main(String[] args) {
new Hello().count1(); // 匿名对象,只能使用一次
Hello t2 = new Hello();
t2.count2(); // 100
t2.count2(); // 101
}
}