求助java编程问题: 某城市用水实行阶梯计费,规则如下:对于生活用...
发布网友
发布时间:2024-09-05 02:34
我来回答
共2个回答
热心网友
时间:2024-09-15 21:50
package demo;//包名
/**
* 某城市用水实行阶梯计费,规则如下:
* 1.对于生活用水:
* 如果月用水量10吨以下,则按2.5元/吨收费,超出部分按3.0元/吨收费;
* 2.对于商业用水:如果用水量20吨以下,则按3.9元/吨收费,超出部分按4.8元 /吨收费。
* 请编写水费类,根据以上阶梯计费方法计算并输出水费,然后写出测试类测试该类(类的基本实现)。
* 测试数据: 生活用水 16吨;商业用水35吨
* 提示:水费类可包含两参数:类别、用水量
*
*/
public class WaterRates {//类名 Water : 水 Rate : 价格
//category : 种类 我们用1代表生活用水,2代表工业用水
private int category;
//用水量
private int waterConsumption;
//构造方法
public WaterRates(int category, int waterConsumption) {
this.category = category;
this.waterConsumption = waterConsumption;
}
//计费
public double charging() {
double price = 0;
//switch - case 可以换成if,这样方便扩展
switch(this.category) {
case 1:
price = charging1();
break;
case 2:
price = charging2();
break;
}
return price;
}
//生活用水计费 -- 各项数字都可以换成常量,方便代码维护
private double charging1() {
if(this.waterConsumption <= 10) {
return 2.5 * this.waterConsumption;
}else {
return 3.0 * (this.waterConsumption - 10) + 25;
}
}
//工业用水计费
private double charging2() {
if(this.waterConsumption <= 20) {
return 3.9 * this.waterConsumption;
}else {
return 4.8 * (this.waterConsumption - 20) + (3.9 * 20);
}
}
//属性的访问方法
public int getCategory() {
return category;
}
public int getWaterConsumption() {
return waterConsumption;
}
//属性的设置方法
public void setCategory(int category) {
this.category = category;
}
public void setWaterConsumption(int waterConsumption) {
this.waterConsumption = waterConsumption;
}
@Override
public String toString() {
String str = "生活用水";
if(this.category == 2) {
str = "工业用水";
}
return str + ":用水量" + waterConsumption + "吨。";
}
}
//测试类
package demo;
/**
* 测试水费类
* 测试数据: 生活用水 16吨;商业用水35吨
*/
public class TestWater {
public static void main(String[] args) {
WaterRates water1 = new WaterRates(1,16);
WaterRates water2 = new WaterRates(2,35);
//获取水费
double price1 = water1.charging();
double price2 = water2.charging();
System.out.println(water1 + "水费共计:" + price1 + "元");
System.out.println(water2 + "水费共计:" + price2 + "元");
}
}
热心网友
时间:2024-09-15 21:54
public class WaterRate {
int type;
int quantity;
public WaterRate(int type, int quantity) {
super();
this.type = type;
this.quantity = quantity;
}
public double calc(){
double cash=0;
if(type==1){
if(quantity>10){
cash = 10*2.5+(quantity-10)*3;
}else{
cash = quantity*2.5;
}
System.out.print("生活用水"+quantity+"吨,总计:");
}else if(type==2){
if(quantity>20){
cash = 10*3.9+(quantity-10)*4.8;
}else{
cash = quantity*3.9;
}
System.out.print("商业用水"+quantity+"吨,总计:");
}else{
System.out.println("请输入正确的类型(1生活用水2商业永硕)");
}
System.out.println(cash+"元");
return cash;
}
public static void main(String[] args) {
new WaterRate(1, 16).calc();
new WaterRate(2, 35).calc();
}
}