第四次上机
- 编写“电费管理类”及其测试类。
- 第一步 编写“电费管理”类
- 私有属性:上月电表读数、本月电表读数
- 构造方法:无参、2个参数
- 成员方法:getXXX()方法、setXXX()方法
- 成员方法:显示上月、本月电表读数
- 第二步 编写测试类
- 创建对象一:上月电表读数为1000,本月电表读数为1200。
要求:调用无参构造方法创建对象;
调用setXXX()方法初始化对象;
假设每度电的价格为1.2元,计算并显示本月电费。
- 创建对象二:上月电表读数1200,本月电表读数为1450。
要求:调用2个参数的构造方法创建并初始化对象;
调用setXXX()方法修改本月电表读数为1500(模拟读错了需修改);
假设每度电的价格为1.2元,计算并显示本月电费。
程序:
package ccc;
public class electricity {//electricity(电量的意思)
private int a;
private int b;
public electricity() {}
public electricity(int a,int b) {
this.a=a;
this.b=b;
}
public int getlast(){
return a;
}
public void setlast(int a){
if(a<0){
this.a=0;
}else{
this.a=a;
} }
public int getnow(){
return b;
}
public void setnow(int b){
if(b<0){
this.b=0;
}else{
this.b=b;
}}
public void print1(){
System.out.println("(对象1)本月电费=:"+1.2*b);
}
public void print2(){
System.out.println("(对象2)本月电费=:"+1.2*b);
}
public static void main(String[]args){ //主函数
electricity p1=new electricity(1000,1200);
p1.print1();
electricity p2=new electricity(1200,1450);
p2.setnow(1500); //将原本的1450改为1500
p2.print2(); }}
运算结果:
2.1 “圆柱体”类
- 私有属性:圆底半径、高,
- 构造方法:带两个参数
- 方法1:计算底面积
- 方法2:计算体积
- 方法3:打印圆底半径、高、底面积和体积。
2.2 测试类
创建2个对象,并调用方法
程序:
package ccc;
public class cylinder {//圆柱体的意思
private int r;
private int h;
public cylinder () {}
public cylinder (int r,int h) {
this.r=r;
this. h= h;
}
//
public int getR(){
return r;
}
public void setR(int r){
if(r<0){
this.r=0;
}else{
this.r=r;
} }
//
public int getH(){
return h;
}
public void setH(int h){
if( h<0){
this. h=0;
}else{
this. h= h;
}}
//
public void S(){
System.out.println("圆柱体的底面积=:"+r*r*3.14);
}
public void V(){
System.out.println("(圆柱体的体积=:"+3.14*r*r*h);
}
public static void main(String[]args){ //主函数
cylinder p1=new cylinder();
p1.setR(6);
p1.setH(5);
p1.S();
p1.V();
}}
运算结果:
3、编写“四则运算类”及其测试类。
3.1 应用场景
计算器。能实现简单的四则运算,要求:只进行一次运算。
3.2“四则运算”类
- 私有属性:操作数一、操作数二、操作符
- 构造方法:带两个参数
- 构造方法:带三个参数
- 方法一:对两个操作数做加运算
- 方法二:对两个操作数做减运算
- 方法三:对两个操作数做乘运算
- 方法四:对两个操作数做除运算
3.3 测试类
从键盘输入两个操作数和一个操作符,计算之后,输出运算结果。
程序:
package ccc;
import java.util.*;
public class 算法 {
static int a;
static int b;
static String c;
public 算法 (int a,int b,String c) {
this.a=a;
this.b= b;
this.c=c;
}
public int l1(){
return a+b;
}
public int l2(){
return a-b;
}
public int l3(){
return a*b;
}
public int l4(){
return a/b;
}
public static void main(String[]args){
System.out.println("输入两个数据和运算符号:");
int d=0;
Scanner k= new Scanner(System.in);
算法 text=new 算法(a,b,c);
text.a=k.nextInt();
text.b=k.nextInt();
text.c=k.next();
if(text.c.hashCode()=="+".hashCode()){//hashCode百度找
d=text.l1();
}else if(text.c.hashCode()=="-".hashCode()){
d=text.l2();
}else if(text.c.hashCode()=="*".hashCode()){
d=text.l3();
}else if(text.c.hashCode()=="/".hashCode()){
d=text.l4();}
System.out.println("结果为:"+d);
}
}
运算结果: