方法封装获取最大值
class 数组获取最大值
{
public static void main(String[] args)
{
int[] array = {32,18,4,98};
//创建一个数值来存储返回值
int temp = max(array);
System.out.println("最大值为"+temp);
}
/*思路:
一维数组获取最大值,按用排序的方法把最大值排出来。
*/
public static int max(int[] arr){
//创建for循环进行排序(冒泡排序)
for(int x = arr.length-1;x >0 ;x--){
for(int y = 0;y<x;y++){
int z = y+1;
if(arr[y]<arr[z]){
int temp = arr[y];
arr[y] = arr[z];
arr[z] = temp;
}
}
}
return arr[0];
}
}
类封装获取最大值
class 数组获取最大值
{
public static void main(String[] args)
{
int[] array = {32,18,4,98};
//想要使用ArrayTool中的功能需要先建立ArrayTool类应用程序的对象,通过new完成。(这个就是对象,所有功能都在对象中,不需要关注功能细节)
ArrayTool tool = new ArrayTool();
//创建变量存储返回值,tool(ArrayTool)下的max方法
int temp1 =tool.max(array);
//创建变量存储返回值,tool(ArrayTool)下的min方法
int temp2 =tool.min(array);
System.out.println("最大值为"+temp1+","+"最小值为"+temp2);
}
}
/*
需求:其他类也需要使用,最大值与最小值
思路:用类封装起来,只要找到功能所属的类就可以
*/
class ArrayTool{
//获取最小值
public static int max(int[] arr){
for(int x = arr.length-1;x >0 ;x--){
for(int y = 0;y<x;y++){
int z = y+1;
if(arr[y]<arr[z]){
int temp = arr[y];
arr[y] = arr[z];
arr[z] = temp;
}
}
}
return arr[0];
}
//获取最小值
public static int min(int[] arr){
for(int x = arr.length-1;x >0 ;x--){
for(int y = 0;y<x;y++){
int z = y+1;
if(arr[y]>arr[z]){
int temp = arr[y];
arr[y] = arr[z];
arr[z] = temp;
}
}
}
return arr[0];
}
}