【JAVA习题300道】-方法与构造方法2

第六题 get方法和set方法

定义一个类,该类有一个成员变量,通过构造方法将其进行赋初值,并提供该成员的getXXX()和setXXX()方法
提示:假设有String name;

package com.jiaguwen.myjava;

public class _6GetSet {
	public int id;
	public String name;
	public void setName(String name){
		this.name=name;
	}
	public String getName(){
		return this.name;
	}
	public static void main(String[] args){
		com.jiaguwen.myjava._6GetSet gs=new com.jiaguwen.myjava._6GetSet();
		gs.setName("窦浴智");
		System.out.println(gs.getName());
	}
}

第七题 构造方法与重载

为“无名的粉”写一个类:class WuMingFen 要求:
1.有三个属性:面码:String theMa 粉的份量(两):int quantity
是否带汤:boolean likeSoup
2.写一个构造方法,以便于简化初始化过程,如:
WuMingFen f1 = new WuMingFen(“牛肉”,3,true);
3.重载构造方法,使得初始化过程可以多样化:
WuMingFen f2 = new WuMingFen(“牛肉”,2);
4.如何使得下列语句构造出来的粉对象是酸辣面码、2两、带汤的?
WuMingFen f3 = new WuMingFen();
5.写一个普通方法:check(),用于查看粉是否符合要求。即:将对象的三个属性打印在控制台上。

package com.java.construction_methods;
public class _7WuMingFen {
	public String theMa;
	public int quantity;
	public boolean likeSoup;
	public _7WuMingFen(){
	}
	public _7WuMingFen(String theMa, int quantity, boolean likeSoup){
		this.theMa=theMa;
		this.quantity=quantity;
		this.likeSoup=likeSoup;
	}
	public _7WuMingFen(String theMa, int quantity){
		this.theMa=theMa;
		this.quantity=quantity;
	}
	public void show(){
		System.out.println("面码:"+this.theMa+",粉的份量(两):"+this.quantity+",是否带汤:"+this.likeSoup);
	}
	public static void main(String[] args){
		_7WuMingFen f1 = new _7WuMingFen("牛肉",3,true);
		_7WuMingFen f2 = new _7WuMingFen("牛肉",2);
		_7WuMingFen f3 = new _7WuMingFen("酸辣面码",2,true);
		f1.show();
		f2.show();
		f3.show();
	}
}

第八题 构造方法的重载

在程序中,经常要对时间进行操作,但是并没有时间类型的数据。那么,我们可以自己实现一个时间类,来满足程序中的需要。
定义名为MyTime的类,其中应有三个整型成员:时(hour),分(minute),秒(second), 为MyTime类定义构造方法,以方便创建对象时初始化成员变量。
再定义diaplay方法,用于将时间信息打印出来。
为MyTime类添加以下方法:
addSecond(int sec)
addMinute(int min)
addHour(int hou)
subSecond(int sec)
subMinute(int min)
subHour(int hou)
分别对时、分、秒进行加减运算。

package com.java.construction_methods;

import java.util.Scanner;
public class _8MyTime {
	public int hour;
	public int minute;
	public int second;

	//构造函数
	public _8MyTime(){}
	public _8MyTime(int hour, int minute, int second){
		this.hour=hour;
		this.minute=minute;
		this.second=second;
	}

	public static void main(String[] args){
		_8MyTime mytime=new _8MyTime(8,56,30);
		mytime.display();
		while(true){
			Scanner sc=new Scanner(System.in);
			System.out.print("输入增加小时:");
			mytime.addHour(Integer.parseInt(sc.nextLine()));
			System.out.print("输入增加分钟:");
			mytime.addMinute(Integer.parseInt(sc.nextLine()));
			System.out.print("输入增加秒:");
			mytime.addSecond(Integer.parseInt(sc.nextLine()));
			System.out.print("输入减少小时:");
			mytime.subHour(Integer.parseInt(sc.nextLine()));
			System.out.print("输入减少分钟:");
			mytime.subMinute(Integer.parseInt(sc.nextLine()));
			System.out.print("输入减少秒:");
			mytime.subSecond(Integer.parseInt(sc.nextLine()));
		}

	}

	//显示
	public void display(){
		System.out.println(">>>>>>当前时间:"+this.hour+"h:"+this.minute+"m:"+this.second+"s<<<<<<");
	}

	//增加秒
	public void addSecond(int sec){
		this.second+=sec;
		if(this.second>=60){
			this.addMinute(this.second/60);
		}
		this.second=this.second%60;
		this.display();
	}

	//增加分
	public void addMinute(int min){
		this.minute+=min;
		while(this.minute>=60){
			this.minute=this.minute-60;
			this.hour+=1;
		}
		this.display();
	}

	//增加小时
	public void addHour(int hou){
		this.hour+=hou;
		this.display();
	}

	//减少秒
	public void subSecond(int sec){
		if(sec>3600){
			this.hour-=sec/3600;
			sec=sec%3600;
		}
		if(sec>60){
			this.minute-=(sec/60);
			sec=sec%60;
		}
		if (this.second-sec>=0){
			this.second-=sec;
		}else {
			this.second=(60+this.second)-sec;
			this.minute-=1;
		}
		this.display();
	}
	//减少分
	public void subMinute(int min){
		if(min>60){
			this.hour-=(min/60);
			min=min%60;
		}
		if (this.minute-min>=0){
			this.minute-=min;
		}else{
			this.minute=(60+this.minute)-min;
			this.hour-=1;
		}
		this.display();
	}

	//减少小时
	public void subHour(int hou){
		this.hour-=hou;
		this.display();
	}
}

第九题 构造方法与重载

定义一个牛肉面的类(Noodle),它的属性有,
牛肉面宽度 width
尺寸:size (大碗还是小碗) 大碗8元,小碗6元
是否加肉:beef :加肉+4元
加蛋的数量:eggs :每个1元;
定义构造方法来根据不同的条件创建不同的牛肉面
Noodle(){
//不加肉,大碗,不加蛋,中宽;
}
Noodle(String width,int size)
Noodle(String width,int size,boolean beef);
Noodle(String width,int size,boolean beef,int eggs);
再定义一个方法,用来显示当前牛肉面的信息,并显示金额;
void showNoodleInfo();

package com.java.construction_methods;

public class _9Noodle {
	public String width;
	public String size;
	public boolean beef;
	public int eggs;
	public _9Noodle(){
		//不加肉,大碗,不加蛋,中宽;
		this.width="中宽";
		this.size="大碗";
		this.beef=false;
		this.eggs=0;
	}
	public _9Noodle(String width, String size){
		this.width=width;
		this.size=size;
	}
	public _9Noodle(String width, String size, boolean beef){
		this.width=width;
		this.size=size;
		this.beef=beef;
	}
	public _9Noodle(String width, String size, boolean beef, int eggs){
		this.width=width;
		this.size=size;
		this.beef=beef;
		this.eggs=eggs;
	}
	public void showNoodleInfo(){
		int money=0;
		if(this.size.equals("大碗")){
			money=8;
		}else if(this.size.equals("小碗")){
			money=6;
		}
		if(this.beef)
			money+=4;
		if(this.eggs>0)
			money+=this.eggs;
		System.out.println(">>>>>>当前菜单---面码:"+this.size+"  是否加肉:"+this.beef+"  加蛋数量:"+this.eggs+"  面宽度:"+this.width+"  总价:"+money+"<<<<<<");
	}
	public static void main(String[] args){
		_9Noodle nood1=new _9Noodle();
		nood1.showNoodleInfo();
		_9Noodle nood2=new _9Noodle("中宽","大碗",true,5);
		nood2.showNoodleInfo();

	}

}

【练习题】10.构造方法与重载、包

编写Addition类,该类中应包含一组实现两数相加运算的重载方法。
实现加法运算的方法,应接受两个参数(即加数和被加数),方法将两个参数进行加法运算后,返回相加结果。考虑可能针对不同的数据类型进行计算,重载一组方法,包括整型、长整型、浮点型、双精度浮点型、还有字符串。 在main方法中创建Addition类的实例,分别调用重载方法测试其效果。 应将Addition类打入到包中,以自己名字的拼音为包命名。

package com.java.construction_methods;

public class _10Addition {
	public int _int;
	public long _long;
	public float _float;
	public double _double;
	public String _String;
	public void add(int _int,long _long){
		System.out.println("int+long:"+(_int+_long));
	}
	public static void main(String[] args){
		_10Addition add1=new _10Addition();
		add1.add(1,123L);
	}
}

【练习题】11.构造方法与重载

定义一个网络用户类,要处理的信息有用户ID、用户密码、email地址。在建立类的实例时,把以上三个信息都作为构造函数的参数输入,其中用户ID和用户密码时必须的,缺省的email地址是用户ID加上字符串"@gameschool.com"

package com.java.construction_methods;

public class _11User {
    public String id;
    public String password;
    public String email;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public _11User(){}
    public _11User(String id, String password){
        this.id=id;
        this.password=password;
        this.email=this.id+"@gameschool.com";
    }
    public void show(){
        System.out.println("用户名:"+this.id+",密码:"+this.password+",Email:"+this.email);
    }
    public static void main(String[] args) {
        _11User user1=new _11User("douyuzhi","dyz123456789");
        user1.show();
    }
}

【练习题】12.构造方法与重载

建立一个汽车类,包括轮胎个数,汽车颜色,车身重量等属性。并通过不同的构造方法创建事例。
至少要求:汽车能够加速,减速,停车。
要求:命名规范,代码体现层次,有友好的操作提示。

package com.java.construction_methods;

public class _12Car {
    public int tyreNum;
    public String carColor;
    public int carWeight;
    public _12Car(){}
    public _12Car(int tyreNum, String carColor, int carWeight){
        this.tyreNum=tyreNum;
        this.carColor=carColor;
        this.carWeight=carWeight;
    }
    public _12Car(int tyreNum, int carWeight){
        this.tyreNum=tyreNum;
        this.carWeight=carWeight;
    }

    public void show(){
        System.out.println("汽车轮胎个数:"+this.tyreNum+",颜色:"+this.carColor+",重量:"+this.carWeight+"KG");
    }

    public void speedUp(){
        int speed=(int)(Math.random()*10)+1;
        System.out.println("踩油门了,加速成功,速度:+"+speed+"m/s");
    }
    public void speedDown(){
         int speed=(int)(Math.random()*10)+1;
        System.out.println("踩刹车了,减速成功,速度:-"+speed+"m/s");
    }
    public void stop(){
        System.out.println("刹车踩到底了,车停了下来");
    }
    public static void main(String[] args) {
        _12Car car1 =new _12Car(4,"白色",1000);
        car1.show();
        _12Car car2 =new _12Car(5,2000);
        car2.show();
        car2.speedUp();
        car2.speedDown();
        car2.stop();
        /**
         * 测试随机数0-1概率
         */
        int[] arr=new int[10000];
        for (int i=0;i<10000;i++){
            arr[i]=(int)(Math.random()*2);
        }
        int zeroNum=0;
        int one=0;
        for (int i=0;i<10000;i++){
            if(arr[i]==0)
                zeroNum++;
            else
                one++;
        }
        System.out.println("0个数:"+zeroNum+",1个数:"+one);
    }
}

【练习题】13.构造方法与重载

创建一个类,为该类定义三个构造函数,分别执行下列操作:
1、传递两个整数值并输出其中较大的一个值
2、传递三个double值并计算出其乘积,将结果输出
3、传递两个字符串值并将它们连接到一起后输出
4、在main方法中测试构造函数的调用

package com.java.construction_methods;

public class _13Num {
    public void _numMax(int a,int b){
        if (b>a)
            a=b;
        System.out.println("最大数为:"+a);
    }
    public void chengJi(double a,double b,double c){
        System.out.println("乘积为:"+(a*b*c));
    }
    public void lianJie(String a,String b){
        System.out.println("连接后:"+a+b);
    }

    public static void main(String[] args) {
        _13Num num1=new _13Num();
        num1._numMax(6,10);
        num1.chengJi(0.1,0.5,0.1);
        num1.lianJie("前连接","后连接");
    }


}

【练习题】14.类的综合练习

1、写一个名为Account的类模拟账户。该类的属性和方法如下图所示。该类包括的属性:账号id,余额balance,年利率annualInterestRate;包含的方法:访问器方法(getter和setter方法),取款方法withdraw(),存款方法deposit()。
Account
private int id
private double balance
private double annualInterestRate
public Account (int id, double balance, double annualInterestRate )
public int getId()
public double getBalance()
public double getAnnualInterestRate()
public void setId( int id)
public void setBalance(double balance)
public void setAnnualInterestRate(double annualInterestRate)
public void withdraw (double amount)
public void deposit (double amount)
提示:在提款方法withdraw中,需要判断用户余额是否能够满足提款数额的要求,如果不能,应给出提示。

2 创建Customer类。
Customer
private String firstName
private String lastName
private Account account
public Customer(String f,String l)
public String getFirstName()
public String getLastName()
public Account getAccount()
public void setAccount(Account account)

a. 声明三个私有对象属性:firstName、lastName和account。
b. 声明一个公有构造器,这个构造器带有两个代表对象属性的参数(f和l)
c. 声明两个公有存取器来访问该对象属性,方法getFirstName和getLastName返回相应的属性。
d. 声明setAccount 方法来对account属性赋值。
e. 声明getAccount 方法以获取account属性。

3.写一个测试程序。
(1) 创建一个Customer ,名字叫 Jane Smith, 他有一个账号为1000,余额为2000元,年利率为 1.23% 的账户。
(2) 对Jane Smith操作。
存入 100 元,再取出960元。再取出2000元。
打印出Jane Smith 的基本信息

Account类

package com.java.construction_methods;

import java.util.Scanner;

public class _14Account {
    public int id;
    public double balance;
    public double annualInterestRate;

    public _14Account() {
    }

    public _14Account(int id, double balance, double annualInterestRate) {
        this.id = id;
        this.balance = balance;
        this.annualInterestRate = annualInterestRate;
    }

    public int getId() {
        return this.id;
    }

    public double getBalance() {
        return this.balance;
    }

    public double getAnnualInterestRate() {
        return this.annualInterestRate;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public void setAnnualInterestRate(double annualInterestRate) {
        this.annualInterestRate = annualInterestRate;
    }

    public void withdraw(double amount) {
        if (this.balance - amount >= 0)
            this.balance -= amount;
        else
            System.out.println("余额不足提取失败");
    }

    public void deposit(double amount) {
        this.balance += amount;
    }

    public void display() {
        System.out.println("你的金额为:" + this.balance);
    }

    public void out(String str) {
        System.out.println(str);
    }

    public static void main(String[] args) {
        _14Account ac = new _14Account(1, 200.5, 0.03d);
        ac.display();
        Scanner sc = new Scanner(System.in);
        ac.out("请输入取款金额:");
        ac.withdraw(Double.parseDouble(sc.nextLine()));
        ac.display();
        ac.out("请输入存款金额:");
        ac.deposit(Double.parseDouble(sc.nextLine()));
        ac.display();
    }
}

Customer类

package com.java.construction_methods;
import com.java.construction_methods._14Account;
public class _14Customer {
    private String firstName;
    private String lastName;
    private _14Account account;
    public _14Customer(){}
    public _14Customer(String f,String l){
        this.firstName=f;
        this.lastName=l;
    }

    public static void main(String[] args) {
        _14Customer cus=new _14Customer("Jane","Smith");
        cus.account=new _14Account(1000,2000,1.23);
        cus.display();
        cus.account.deposit(100);
        cus.account.withdraw(960);
        cus.account.withdraw(2000);
        cus.display();


    }

    public String getFirstName(){
        return this.firstName;
    }

    public String getLastName(){
        return this.lastName;
    }

    public _14Account getAccount(){
        return this.account;
    }

    public void setAccount(_14Account account){
        this.account=account;
    }

    public void display(){
        System.out.println("尊敬的用户:"+this.firstName+this.lastName+",账号序号:"+this.account.id+",余额;"+this.account.balance+"$$,当前年利率:"+this.account.annualInterestRate);
    }

}

  • 1
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值