0
点赞
收藏
分享

微信扫一扫

Java~面向对象(上)练习题

大师的学徒 2022-04-15 阅读 35

类的属性 方法练习题

创建一个Person类,其定义如下:

public class Person {
	String name;
	int age;
	/*
	 * sex:1表示为男性
	 * sex:0表示为女性
	 */
	int sex;
	
	public void study(){
		System.out.println("studying");
	}
	
	public void showAge(){
		System.out.println("age:" + age);
	}
	
	public int addAge(int i){
		age += i;
		return age;
	}
}

测试类

public class PersonTest {
	public static void main(String[] args) {
		Person p1 = new Person();
		
		p1.name = "Tom";
		p1.age = 18;
		p1.sex = 1;
		
		p1.study();
		
		p1.showAge();
		
		int newAge = p1.addAge(2);//用int型接受,下面要用到这个改变的年龄
		System.out.println(p1.name + "的年龄为" + newAge);
		
		System.out.println(p1.age);	//20
		
		//*******************************
		Person p2 = new Person();
		p2.showAge();	//0
		p2.addAge(10);//也可以不用int类型接受,但是age已经改变
		p2.showAge();	//10
		
		p1.showAge();	//20
	}
}
对象数组题目:
定义类Student,包含三个属性:学号number(int),年级state(int),成绩score(int)。
创建20个学生对象,学号为1到20,年级和成绩都由随机数确定。
问题一:打印出3年级(state值为3)的学生信息。
问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息

提示:
1) 生成随机数:Math.random(),返回值类型double;
2) 四舍五入取整:Math.round(double d),返回值类型long。
public class StudentTest {
	public static void main(String[] args) {
		
//		Student s1 = new Student();//new20个对象
//		Student s1 = new Student();
//		Student s1 = new Student();
//		Student s1 = new Student();
//		Student s1 = new Student();
//		Student s1 = new Student();
		
		//声明Student类型的数组
		Student[] stus = new Student[20];  //String[] arr = new String[10];
		//用Student类型的数组存放
		for(int i = 0;i < stus.length;i++){
			//给数组元素赋值
			stus[i] = new Student();//给每一个元素new一个对象,stus[i]就是对象
			//给Student对象的属性赋值
			stus[i].number = (i + 1);
			//年级:[1,6]
			stus[i].state = (int)(Math.random() * (6 - 1 + 1) + 1);
			//成绩:[0,100]
			stus[i].score = (int)(Math.random() * (100 - 0 + 1));
		}
		
		//遍历学生数组
		for(int i = 0;i <stus.length;i++){
//			System.out.println(stus[i].number + "," + stus[i].state 
//					+ "," + stus[i].score);
			
			System.out.println(stus[i].info());
		}
		
		System.out.println("********************");
		
		//问题一:打印出3年级(state值为3)的学生信息。
		for(int i = 0;i <stus.length;i++){
			if(stus[i].state == 3){
				System.out.println(stus[i].info());
			}
		}
		
		System.out.println("********************");
		
		//问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息
		for(int i = 0;i < stus.length - 1;i++){
			for(int j = 0;j < stus.length - 1 - i;j++){
				if(stus[j].score > stus[j + 1].score){
					//如果需要换序,交换的是数组的元素:Student对象!!!
					Student temp = stus[j];//[注意]:Student temp  这里是将整个对象换位置
					stus[j] = stus[j + 1];
					stus[j + 1] = temp;
				}
			}
		}
		
		//遍历学生数组
		for(int i = 0;i <stus.length;i++){
			System.out.println(stus[i].info());
		}
		
	}
}

class Student{
	int number;//学号
	int state;//年级
	int score;//成绩
	
	//显示学生信息的方法
	public String info(){
		return "学号:" + number + ",年级:" + state + ",成绩:" + score;//谁调用就是谁的
	}
}

练习2优化(用封装的思想)

//此代码是对StudentTest.java的改进:将操作数组的功能封装到方法中。
//优化时是将遍历 冒泡 查找三种方法封装到StudentTest1类中的,所以建立对象要用StudentTest1类,也可以新建立一个类,用这个类new对象。(方法不能套方法)

public class StudentTest1 {
	public static void main(String[] args) {
		
		//声明Student类型的数组
		Student1[] stus = new Student1[20];  
		
		for(int i = 0;i < stus.length;i++){
			//给数组元素赋值
			stus[i] = new Student1();
			//给Student对象的属性赋值
			stus[i].number = (i + 1);
			//年级:[1,6]
			stus[i].state = (int)(Math.random() * (6 - 1 + 1) + 1);
			//成绩:[0,100]
			stus[i].score = (int)(Math.random() * (100 - 0 + 1));
		}
		
		StudentTest1 test = new StudentTest1();
		
		//遍历学生数组
		test.print(stus);
		
		System.out.println("********************");
		
		//问题一:打印出3年级(state值为3)的学生信息。
		test.searchState(stus, 3);
		
		System.out.println("********************");
		
		//问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息
		test.sort(stus);
		
		//遍历学生数组
		test.print(stus);
		
	}
	
	/**
	 * 
	 * @Description  遍历Student1[]数组的操作
	 * @author shkstart
	 * @date 2019年1月15日下午5:10:19
	 * @param stus
	 */
	public void print(Student1[] stus){
		for(int i = 0;i <stus.length;i++){
			System.out.println(stus[i].info());
		}
	}
	/**
	 * 
	 * @Description 查找Stduent数组中指定年级的学生信息
	 * @author shkstart
	 * @date 2019年1月15日下午5:08:08
	 * @param stus 要查找的数组
	 * @param state 要找的年级
	 */
	public void searchState(Student1[] stus,int state){//在那个数组中找,找那个年纪的
		for(int i = 0;i <stus.length;i++){
			if(stus[i].state == state){
				System.out.println(stus[i].info());
			}
		}
	}
	
	/**
	 * 
	 * @Description 给Student1数组排序
	 * @author shkstart
	 * @date 2019年1月15日下午5:09:46
	 * @param stus
	 */
	public void sort(Student1[] stus){
		for(int i = 0;i < stus.length - 1;i++){
			for(int j = 0;j < stus.length - 1 - i;j++){
				if(stus[j].score > stus[j + 1].score){
					//如果需要换序,交换的是数组的元素:Student对象!!!
					Student1 temp = stus[j];
					stus[j] = stus[j + 1];
					stus[j + 1] = temp;
				}
			}
		}
	}
}

class Student1{
	int number;//学号
	int state;//年级
	int score;//成绩
	
	//显示学生信息的方法
	public String info(){
		return "学号:" + number + ",年级:" + state + ",成绩:" + score;
	}
}

方法参数的值传递机制练习题

public class TransferTest3{
	public static void main(String args[]){
		TransferTest3 test=new TransferTest3();
		test.first();
	}
	
	public void first(){
		int i=5;
		Value v=new Value();
		v.i=25;
		second(v,i);
		System.out.println(v.i);
	}
	
	public void second(Value v,int i){
		i=0;
		v.i=20;
		Value val=new Value();
		v=val;
		System.out.println(v.i+" "+i);
		
	}
}
class Value {
	int i= 15;
} 

public static void method(int a,int b){
	a = a * 10;
	b = b * 20;
	System.out.println(a);
	System.out.println(b);
	System.exit(0);//不让main方法中的Sysout输出
}
微软:
定义一个int型的数组:int[] arr = new int[]{12,3,3,34,56,77,432};
让数组的每个位置上的值去除以首位置的元素,得到的结果,作为该位置上的新值。遍历新的数组。
//错误写法
for(int i= 0;i < arr.length;i++){
	arr[i] = arr[i] / arr[0];
}

//正确写法1, 倒着写
for(int i = arr.length –1;i >= 0;i--){
	arr[i] = arr[i] / arr[0];
}

//正确写法2
int temp = arr[0];
for(int i= 0;i < arr.length;i++){
	arr[i] = arr[i] / temp;
}
int[] arr = new int[10];
System.out.println(arr);//地址值?

char[] arr1 = new char[10];
System.out.println(arr1);//地址值?
public class ArrayPrint {

	public static void main(String[] args) {
		int[] arr = new int[]{1,2,3};
        //传进去的是一个Object的对象
		System.out.println(arr);//地址值
		
		char[] arr1 = new char[]{'a','b','c'};
        //传进去的是一个数组,里面遍历数据了
		System.out.println(arr1);//abc
	}
}
(1)定义一个Circle类,包含一个double型的radius属性代表圆的半径,一个findArea()方法返回圆的面积。
(2)定义一个类PassObject,在类中定义一个方法printAreas(),该方法的定义如下:
public void printAreas(Circle c,int time)
在printAreas方法中打印输出1到time之间的每个整数半径值,以及对应的面积。
例如,times为5,则输出半径1,2,3,4,5,以及对应的圆面积。
(3)在main方法中调用printAreas()方法,调用完毕后输出当前半径值。
public class Circle {

	double radius;	//半径
	
	//返回圆的面积
	public double findArea(){
		return radius * radius * Math.PI;
	}
}

PassObject类

public class PassObject {
	
	public static void main(String[] args) {
		PassObject test = new PassObject();
		
		Circle c = new Circle();
		
		test.printAreas(c, 5);
	}
	
	public void printAreas(Circle c,int time){
		
		System.out.println("Radius\t\tAreas");
		
		//设置圆的半径
		for(int i = 1;i <= time ;i++){
			c.radius = i;
			System.out.println(c.radius + "\t\t" + c.findArea());
		}
	}
}

递归练习题

public class RecursionTest {

	public static void main(String[] args) {

		int value = test.f(10);
		System.out.println(value);
	}

	//例3:已知有一个数列:f(0) = 1,f(1) = 4,f(n+2)=2*f(n+1) + f(n),
	//其中n是大于0的整数,求f(10)的值。
	public int f(int n){
		if(n == 0){
			return 1;
		}else if(n == 1){
			return 4;
		}else{
			return 2*f(n-1) + f(n-2);//f(n)=2*f(n+2) - 2f(n-1)这样写会栈溢出
		}
	}
}
输入一个数据n,计算斐波那契数列(Fibonacci)的第n个值
1 1 2 3 5 8 13 21 34 55
规律:一个数等于前两个数之和
要求:计算斐波那契数列(Fibonacci)的第n个值,并将整个数列打印出来
public class Recursion2 {

	public static void main(String[] args) {
		
		Recursion2 test = new Recursion2();
		int value = test.f(10);
		System.out.println(value);
	}
	
	public int f(int n) {

		if (n == 1 || n == 2) {
			return 1;
		} else {
			return f(n - 1) + f(n - 2);
		}
	}
}

封装性练习题

/*
 * 1.创建程序,在其中定义两个类:Person 和 PersonTest 类。
 * 定义如下:用 setAge()设置人的合法年龄(0~130),用 getAge()返回人的年龄。
 */
public class Person {

	private int age;
	
	public void setAge(int a){
		if(a < 0 || a > 130){
//			throw new RuntimeException("传入的数据据非法");
			System.out.println("传入的数据据非法");
			return;
		}
		age = a;
	}
	
	public int getAge(){
		return age;
	}
}

测试类

/*
 *  在 PersonTest 类中实例化 Person 类的对象 b,
 *  调用 setAge()和 getAge()方法,体会 Java 的封装性。
 */
public class PersonTest {

	public static void main(String[] args) {
		Person p1 = new Person();
//		p1.age = 1;	//编译不通过
		
		p1.setAge(12);
		
		System.out.println("年龄为:" + p1.getAge());
	}
}

构造器练习题

在Person类中添加构造器,
利用构造器设置所有人的 age 属性初始值都为 18。
public class Person {

	private int age;
	
	public Person(){
		age = 18;
	}
    
    public int getAge(){
		return age;
	}
}

public class PersonTest {

	public static void main(String[] args) {
		Person p = new Person();

		System.out.println("年龄为:" + p.getAge());//18
	}
}
修改上题中类和构造器,增加 name 属性,
使得每次创建 Person 对象的同时初始化对象的 age 属性值和 name 属性值。
public class Person {

	private int age;
	private String name;
	
	public Person(){
		age = 18;
	}
	
	public Person(String n,int a){
		name = n;
		age = a;
	}
	
	public void setName(String n){
		name = n;
	}
	
	public String getName(){
		return name;
	}
	
	public void setAge(int a){
		if(a < 0 || a > 130){
//			throw new RuntimeException("传入的数据据非法");
			System.out.println("传入的数据据非法");
			return;
		}
		
		age = a;
		
	}
	
	public int getAge(){
		return age;
	}
}

public class PersonTest {

	public static void main(String[] args) {
		
		Person p2 = new Person("Tom",21);
		
		System.out.println("name = " + p2.getName() + ",age = " + p2.getAge());
	}
}
编写两个类,TriAngle 和 TriAngleTest,
其中 TriAngle 类中声明私有的底边长 base 和高 height,同时声明公共方法访问私有变量。
此外,提供类必要的构造器。另一个类中使用这些公共方法,计算三角形的面积。
public class TriAngle {

	private double base;//底边长
	private double height;//高
	
	public TriAngle(){
		
	}
	
	public TriAngle(double b,double h){
		base = b;
		height = h;
	}
	
	public void setBase(double b){
		base = b;
	}
	
	public double getBase(){
		return base;
	}
	
	public void setHeight(double h){
		height = h;
	}
	
	public double getHeight(){
		return height;
	}
}

public class TriAngleTest {

	public static void main(String[] args) {
		
		TriAngle t1 = new TriAngle();
		t1.setBase(2.0);
		t1.setHeight(2.5);
//		t1.base = 2.5;//The field TriAngle.base is not visible	
		System.out.println("base : " + t1.getBase() + ",height : " + t1.getHeight());
		
		TriAngle t2 = new TriAngle(5.1,5.6);
		System.out.println("面积 : " + t2.getBase() * t2.getHeight() / 2);

	}
}

this关键字练习题

Boy 类

public class Boy {

	private String name;
	private int age;
	
	public void setName(String name){
		this.name = name;
	}
	
	public String getName(){
		return name;
	}
	
	public void setAge(int age){
		this.age = age;
	}
	
	public int getAge(){
		return age;
	}
	
	public Boy(String name, int age) {
		this.name = name;
		this.age = age;
	}


	public void marry(Girl girl){
		System.out.println("我想娶" + girl.getName());
	}
	
	public void shout(){
		if(this.age >= 22){
			System.out.println("可以考虑结婚");
		}else{
			System.out.println("好好学习");
		}
	}
}

Girl 类

public class Girl {
	
	private String name;
	private int age;
	
	public Girl() {

	}
	public Girl(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void marry(Boy boy){
		System.out.println("我想嫁给" + boy.getName());
		boy.marry(this);
	}
	
	/**
	 * 
	 * @Description 比较两个对象的大小,只能比较具体数值,比较地址无意义
	 * @author shkstart
	 * @date 2019年1月18日下午4:02:09
	 * @param girl
	 * @return  正数:当前对象大;  负数:当前对象小  ; 0:当前对象与形参对象相等
	 */
	public int compare(Girl girl){
//		if(this.age > girl.age){
//			return 1;
//		}else if(this.age < girl.age){
//			return -1;
//		}else{
//			return 0;
//		}
		
		return this.age - girl.age;
	}
}

测试类

public class BoyGirlTest {

	public static void main(String[] args) {
		
		Boy boy = new Boy("罗密欧",21);
		boy.shout();
		
		Girl girl = new Girl("朱丽叶", 18);
		girl.marry(boy);
		
		Girl girl1 = new Girl("祝英台", 19);
		int compare = girl.compare(girl1);
		if(compare > 0){
			System.out.println(girl.getName() + "大");
		}else if(compare < 0){
			System.out.println(girl1.getName() + "大");
		}else{
			System.out.println("一样的");
		}
	}
}
题目:实验1:Account_Customer.pdf

Account 类

public class Account {
	private int id;//账号
	private double balance;//余额
	private double annualInterestRate;//年利率
	
	public Account (int id, double balance, double annualInterestRate ){
		this.id = id;
		this.balance = balance;
		this.annualInterestRate = annualInterestRate;
	}

	public int getId() {
		return id;
	}

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

	public double getBalance() {
		return balance;
	}

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

	public double getAnnualInterestRate() {
		return annualInterestRate;
	}

	public void setAnnualInterestRate(double annualInterestRate) {
		this.annualInterestRate = annualInterestRate;
	}
	//在提款方法withdraw中,需要判断用户余额是否能够满足提款数额的要求,如果不能,应给出提示。
	public void withdraw (double amount){//取钱
		if(balance < amount){
			System.out.println("余额不足,取款失败");
			return;
		}
		balance -= amount;
		System.out.println("成功取出:" + amount);
	}
	
	public void deposit (double amount){//存钱
		if(amount > 0){
			balance += amount;
			System.out.println("成功存入:" + amount);
		}
	}
}

Customer 类

public class Customer {
	
	private String firstName;
	private String lastName;
	private Account account;
	
	public Customer(String f,String l){
		this.firstName = f;
		this.lastName = l;
	}

	public Account getAccount() {
		return account;
	}

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

	public String getFirstName() {
		return firstName;
	}

	public String getLastName() {
		return lastName;
	}
}

CustomerTest 类

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

成功存入 :100.0
成功取出:960.0
余额不足,取款失败
Customer [Smith, Jane] has a account: id is 1000, 
annualInterestRate is 1.23%, balance is 1140.0
 */
public class CustomerTest {
	public static void main(String[] args) {
		Customer cust = new Customer("Jane", "Smith");
		
		Account acct = new Account(1000, 2000, 0.0123);//造一个账户
		
		cust.setAccount(acct);
		
		cust.getAccount().deposit(100);
		cust.getAccount().withdraw(960);
		cust.getAccount().withdraw(2000);
		
		System.out.println("Customer[" + cust.getLastName() + "," + cust.getFirstName() + 
				"] has a account: id is " + cust.getAccount().getId() + ",annualInterestRate is "+
		cust.getAccount().getAnnualInterestRate() * 100 + "% ,balance is " + cust.getAccount().getBalance());
	}
}
题目:实验2:Account_Customer_Bank.pdf

Account 类

public class Account {

	private double balance;

	public double getBalance() {
		return balance;
	}

	public Account(double init_balance){
		this.balance = init_balance;
	}
	
	//存钱操作
	public void deposit(double amt){
		if(amt > 0){
			balance += amt;
			System.out.println("存钱成功");
		}
	}
	
	//取钱操作
	public void withdraw(double amt){
		if(balance >= amt){
			balance -= amt;
			System.out.println("取钱成功");
		}else{
			System.out.println("余额不足");
		}
	}
}

Customer 类

public class Customer {

	private String firstName;
	private String lastName;
	private Account account;
	
	public String getFirstName() {
		return firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public Account getAccount() {
		return account;
	}
	public void setAccount(Account account) {
		this.account = account;
	}
	public Customer(String f, String l) {
		this.firstName = f;
		this.lastName = l;
	}	
}

Bank 类

public class Bank {

	private int numberOfCustomers;	//记录客户的个数
	private Customer[] customers;	//存放多个客户的数组
	
	public Bank(){
		customers = new Customer[10];
	}
	
	//添加客户
	public void addCustomer(String f,String l){
		Customer cust = new Customer(f,l);
//		customers[numberOfCustomers] = cust;
//		numberOfCustomers++;
		customers[numberOfCustomers++] = cust;
	}

	//获取客户的个数
	public int getNumberOfCustomers() {
		return numberOfCustomers;
	}

	//获取指定位置上的客户
	public Customer getCustomers(int index) {
//		return customers;	//可能报异常
		if(index >= 0 && index < numberOfCustomers){
			return customers[index];
		}
		
		return null;
	}	
	
}

BankTest 类

public class BankTest {

	public static void main(String[] args) {
		
		Bank bank = new Bank();
		
		bank.addCustomer("Jane", "Smith");	
		
		bank.getCustomers(0).setAccount(new Account(2000));
		
		bank.getCustomers(0).getAccount().withdraw(500);
		
		double balance = bank.getCustomers(0).getAccount().getBalance();
		
		System.out.println("客户: " + bank.getCustomers(0).getFirstName() + "的账户余额为:" + balance);
		
		System.out.println("***************************");
		bank.addCustomer("万里", "杨");
		
		System.out.println("银行客户的个数为: " + bank.getNumberOfCustomers());
		
	}
}
举报

相关推荐

0 条评论