JAVA 数组 面向对象

案例一:使用方法来遍历数组,并创建方法来进行对数组元素排序

 定义方法

public class ArrayMethod {
	//定义一个方法实现数组遍历
	public void printArray(int[] array){
		for(int i =0;i<array.length;i++){
			System.out.print(array[i]+" ");
		}
	}
	
	//定义一个方法实现数组排序
	public void sort(int[] array){
		for (int i = 0; i < array.length-1; i++) {
			for (int j = 0; j < array.length-1-i; j++) {
				if(array[j]>array[j+1]){
					int temp = array[j];
					array[j] = array[j+1];
					array[j+1] = temp;
				}
			}
		}
	}

}

 调用方法

public class ArrayMethodTest {

	public static void main(String[] args) {
		// 创建对象,调用方法
		ArrayMethod am = new ArrayMethod();

		// 声明一个int类型的数组
		int[] nums = { 11, 78, 54, 29, 80, 44, 55 };

		// 遍历数组
		am.printArray(nums);
		System.out.println();//换行
		// 排序
		am.sort(nums);

		// 遍历数组
		am.printArray(nums);
		
		int[] nums2 = {22,3,44,5,1,90,23};
		am.sort(nums2);
		System.out.println();//换行
		// 遍历数组
		am.printArray(nums2);
	

	}

}

 

案例二:

定义饮料,要求 1、属性有品牌和价格。2、创造三个对象:农夫山泉、百世可乐、可口可乐

3、农夫山泉饮料价格上涨3元

定义属性

//定义一个类
public class Woter {
//定义品牌
      public String brand;
//定义价格
      public double price;
}

定义方法


public class WoterMat {

	public void add (Woter[] wt){

		for (int i=0;i<wt.length;i++){
//如果谁的牌子是农夫山泉则价格上涨3元
			if((wt[i].brand).equals("农夫山泉")){
				wt[i].price+=3;
			}
		}
	}

}

赋值 调用方法

public class WoterText {

	public static void main(String[] args) {
//		准备一个数组
		Woter[] wt=new Woter[3];
//		创建对象1
		Woter wt1= new Woter();
		wt1.brand="农夫山泉";
		wt1.price=3;
//		创建对象2
		Woter wt2= new Woter();
		wt2.brand="百世可乐";
		wt2.price=3;
//		创建对象3
		Woter wt3= new Woter();
		wt3.brand="可口可乐";
		wt3.price=3;
//		把对象赋值给数组元素
		wt[0]=wt1;
		wt[1]=wt2;
		wt[2]=wt3;
//		调用方法
		WoterMat mt =new WoterMat();
		mt.add(wt);
//		遍历数组中的价格
		for(int i=0;i<wt.length;i++){
			System.out.println(wt[i].price);
		}
	}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值