Java语法基础练习题3

课堂练习4

编写代码模拟手机与SIM卡的组合关系。

要求:

           SIM卡类负责创建SIM卡;

           Phone类负责创建手机;

          手机可以组合一个SIM卡;

          手机可以更换其中的SIM卡。

package test.sim;
import java.util.Scanner;
public class TestPhone {
public static void main(String[] args) {
Phone phone=new Phone("OPPO");
Sim sim=new Sim("18375433859");
System.out.println("默认手机是"+phone.GetPhone()+"\nSIM卡是"+sim.GetSim());

System.out.println("请输入手机型号:");
Scanner reader=new Scanner(System.in);
String p=reader.next();
phone.setPhone(p);
System.out.println("请输入手机SIM卡号:");
String s=reader.next();
sim.SetSim(s);
System.out.println("新手机是"+phone.GetPhone()+"\nSIM卡是"+sim.GetSim());
}
}

package test.sim;


public class Phone {


String p;
Phone(String p) {
this.p=p;
}
void setPhone(String p) {
this.p=p;
}
String GetPhone(){
return p;
}
}

package test.sim;


public class Sim {
String s;
Sim(String s) {
this.s=s;
}
void SetSim(String s){
this.s=s;
}

String GetSim(){
return s;
}
}


课堂练习5


package test.cpu;


public class Test {
public static void main(String[] args) {
CPU cpu = new CPU();
cpu.setSpeed(200);
HardDisk disk = new HardDisk();
disk.setAmount(200);
PC pc =new PC();
pc.SetCpu(cpu);
pc.SetHardDisk(disk);
pc.show();
}
}

package test.cpu;


public class PC {
CPU cpu;
HardDisk HD;
void SetCpu(CPU c){
cpu = c;
}
void SetHardDisk(HardDisk h){
HD = h;
}
void show(){
System.out.print("CPU的速度是"+cpu.speed+"\n硬盘的容量是:"+HD.amount);
}
}

package test.cpu;


public class HardDisk {
int amount;
void setAmount(int m){
amount = m;
}
int getAmount(){
return amount;
}
}

package test.cpu;


public class CPU {
int speed;
void setSpeed(int m){
speed = m;
}
int getSpeed(){
return speed;
}
}


课堂练习6

– 定义一个圆类(Circle),其所在的包为bzu.info.software;定义一个圆柱类Cylinder,其所在的包为bzu.info.com;定义一个主类A,其所在的包也为bzu.info.com,在A中生成一个Cylinder对象,并输出其体积。编译并运行该类。

– 试着改变求体积方法的访问权限,查看并分析编译和运行结果

– 把Cylinder类和A类置于不同的包中,通过对求体积方法设置不同的访问权限,查看并分析编译和运行结果

package bzu.info.com;
import bzu.info.software.Circle;
public class A {


public static void main(String[] args) {
Circle circle = new Circle(10);
System.out.println("圆的半径"+circle.radius);     //输出圆circle的半径

Cylinder circular = new Cylinder(circle, 20);
System.out.println("圆锥的底圆半径:"+circular.getBottomRadius());    //输出圆锥的底圆半径
System.out.println("圆锥的体积:"+circular.getVolume());    //输出圆锥的体积
}
}

package bzu.info.com;


import bzu.info.software.Circle;


public class Cylinder {
public Circle bottom;
public double height;

public Cylinder(Circle c, double h){
bottom = c;
height = h;
}

double getBottomRadius(){
return bottom.radius;
}

void setBottomRadius(double r){
bottom.radius = r;
}

double getVolume(){
return bottom.getArea()*height/3.0;
}
}

package bzu.info.software;


public class Circle {
public double radius;
public Circle(double r){
radius = r;
}
public double getArea(){
return 3.14*radius*radius;
}
}


已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页