案例一:使用方法来遍历数组,并创建方法来进行对数组元素排序
定义方法
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);
}
}
}