请大虾指点下,java如何求数组的最值问题(思路与代码)

小北cool 2013-04-08 11:29:36
编写程序,实现用户输入5个整数,保存到数组中,然后找到这五个数的最大值.(希望代码和思路都能写上)
...全文
319 8 打赏 收藏 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
java爱好者 2013-04-12
  • 打赏
  • 举报
回复
其实commons-lang 包中 ObjectUtils.max(T...values) 方法很好用,支持泛型。
balabala_sean 2013-04-09
  • 打赏
  • 举报
回复

public class Test{
	public static int getMaxValue(int[] x){
		//bubble sort 
		for(int a=1;a<x.length;a++){
			for(int b=x.length-1;b>=a;b--){
				if(x[b-1]<x[b]){
					int temp = x[b-1]	;
					x[b-1] = x[b];
					x[b] = temp;
				}
			}
		}
		//return max value
		return x[0];
	}
	
	public static void main(String[] args){
		//if you wanted the array inputed by user,you can use the class of Scaner
		int[] test = {1,24,5,2,3};
		int maxValue = getMaxValue(test);
		System.out.println(maxValue);
	}
}
花木兰1闪21A 2013-04-09
  • 打赏
  • 举报
回复
引用
如果你是想代码简单点的话,直接调用Arrays.sort(arr),然后再输出最后那个就ok了
这个同意
attach_finance 2013-04-09
  • 打赏
  • 举报
回复
如果你是想代码简单点的话,直接调用Arrays.sort(arr),然后再输出最后那个就ok了
Mourinho 2013-04-09
  • 打赏
  • 举报
回复
引用 4 楼 x19881216 的回复:
2,3楼不要误导楼主,这种求N大值的问题直接遍历一遍数组就完了,而不是第一时间想到要排序,另外1楼正解
+1 遍历一边就完事了
小绵羊 2013-04-09
  • 打赏
  • 举报
回复
2,3楼不要误导楼主,这种求N大值的问题直接遍历一遍数组就完了,而不是第一时间想到要排序,另外1楼正解
skylinke 2013-04-08
  • 打赏
  • 举报
回复
最值的求法可以用排序,讲数组中的值按从大到小或者从小到大排序,最值就出来了 排序的方法有二分排序,冒泡排序,快速排序,这里代码你随便找一本书就有了
失落夏天 2013-04-08
  • 打赏
  • 举报
回复
这个没什么难度。 楼主还是多锻炼下吧。

public class Test3 {
	public static void main(String[] args) {
		int[] colum=new int[5];
		Scanner s=new Scanner(System.in);
		for(int i=0;i<5;i++){
			colum[i]=s.nextInt();
		}
		System.out.println(getMax(colum));
	}
	public static int getMax(int[] colum){
		int max=colum[0];
		for(int i:colum){
			if(i>max){
				max=i;
			}
		}
		return max;
	}
}

62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧