第五天
java2 实用教程第五版 耿祥义 张跃平编著
第四章代码
代码1:课本P80
package java课本项目;
import java.util.*;
public class Example4_11 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
int [] a= {12,34,5,23,45,6,76,90,69,123,59};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
System.out.println("请输入整数,判断该整数是否在数组中:");
int number = scanner.nextInt();
int index = Arrays.binarySearch(a, number);
if (index>=0)
System.out.println(number+"和数组中索引为"+index+"的元素值相同");
else
System.out.println(number+"不与数组中的任何元素值都不相同");
scanner.close();
}
}
运行结果:
/******************************************************
[5, 6, 12, 23, 34, 45, 59, 69, 76, 90, 123]
请输入整数,判断该整数是否在数组中:
90
90和数组中索引为9的元素值相同
*******************************************************/
代码2:课本P81
package java课本项目;
/* 注:方法重载的意思是:一个类中可以有多个方法具有相同的名字,但这些方法的参数必须不同,即:参数的个数不同,
或参数的个数相同,但参数列表中对应的某个参数的类型不同 如果两个方法的名字相同,
即使返回的类型不同,也必须保证传入的参数不同 */
class People {
float hello(int a,int b) { //方法名相同,传入不同类型的参数
return a+b;
}
float hello(long a,int b) {
return a-b;
}
double hello(double a,int b) {
return a*b;
}
}
public class Example4_12 {
public static void main(String args[]) {
People tom = new People();
System.out.println(tom.hello(10, 20));
System.out.println(tom.hello(10L, 20));
System.out.println(tom.hello(10.0, 20));
}
}
运行结果:
/**********************************
30.0
-10.0
200.0
***********************************/
代码3:课本P82
package java课本项目;
class Circlee {
double radius,area;
void setRadius(double r) {
radius = r;
}
double getArea() {
area = 3.14*radius*radius;
return area;
}
}
class Tixing {
double above,bottom,height;
Tixing (double a,double b,double h) {
above = a;
bottom = b;
height = h;
}
double getArea() {
return (above+bottom)*height/2;
}
}
class Studentt{
double computerArea(Circlee c) { //重载方法1
double area = c.getArea();
return area;
}
double computerArea(Tixing t) { //重载方法2
double area = t.getArea();
return area;
}
}
public class Example4_13 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Circlee circle=new Circlee();
circle.setRadius(196.87);
Tixing lader = new Tixing(3,21,9);
Studentt zhang = new Studentt();
System.out.println("zahng计算圆的面积:");
double result = zhang.computerArea(circle);
System.out.println(result);
System.out.println("zhang计算梯形的面积:");
result = zhang.computerArea(lader);
System.out.println(result);
}
}
运行结果:
/****************************************
zahng计算圆的面积:
121699.48226600002
zhang计算梯形的面积:
108.0
*****************************************/
代码4:课本P84
package java课本项目;
//this关键字出现在类的构造方法中时,代表使用该构造方法所创建的对象
public class Example4_14 {
int leg,hand;
String name;
Example4_14(String s) {
name = s;
this.init(); //可以省略this,即将“this.init()”写成“init()”
}
void init() {
leg = 2;
hand = 2;
System.out.println(name+"有"+hand+"只手"+","+leg+"条腿");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Example4_14 boshi=new Example4_14("布什"); //创建boshi时,构造方法中this就是对象boshi
}
}
<