找二维数组中最大元素所在的位置

kongtangzai 2011-09-21 05:35:38
java编程:对一个给定的4*5的二维数组进行赋值,并且找出各行中最大元素以及其在该行的位置。
public class Shiyan3_11 {
public static void main (String[] args) {
int i,j,row = 0,colum = 0 ,max = 0;
int[][] a = {{70,12,20,13,16},
{30,21,13,17,18},
{18,12,50,65,31},
{32,33,25,24,40},
};
for(i = 0;i < a.length;i++){
for(j = 0;j < a[i].length;j++){
System.out.print(a[i][j] + ",");
}
System.out.println();
}
System.out.println();
for(i = 0;i < a.length;i++){
max = a[i][0];
for(j = 0;j < a[i].length;j++){
if(a[i][j] > max){
max = a[i][j];
colum = j;
}
}
row = i;
int temp = a[i][0];
a[i][0] = a[i][colum];
a[i][colum] = temp;
System.out.println("第"+i+"行的最大数是:a[" + row + "][" + colum +"]=" + max);
}
}
}
运行结果:
70,12,20,13,16,
30,21,13,17,18,
18,12,50,65,31,
32,33,25,24,40,

第0行的最大数是:a[0][0]=70
第1行的最大数是:a[1][0]=30
第2行的最大数是:a[2][3]=65
第3行的最大数是:a[3][4]=40


...全文
811 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
kongtangzai 2011-09-22
  • 打赏
  • 举报
回复
我也是很菜的。以后大家多多交流啊!!
jun921373786 2011-09-22
  • 打赏
  • 举报
回复
这个很简单的啊,下面是最直接的比较方法,你看看,其实最重要的是自己多去思考思考。

public static void GetMaxNbr1(int[][] a) {
int max, x, y;
if (a.length > 0 && a[0].length > 0) {
x=0;
y=0;
max = a[x][y];
for (int i = 0; i < a.length; i++) {
for (int j = 1; j < a[0].length; j++) {
if(a[i][j]>max)
{
x=i;
y=j;
max = a[i][j];
}
}
}

System.out.println("数组a数据最大值位置是:a["+x+"]["+y+"];");
System.out.println("数组a数据最大值是:"+a[x][y]);
}
}
niuniu20008 2011-09-22
  • 打赏
  • 举报
回复

public class FindMax {

public static void main(String[] args) {
int[][] arr = { { 70, 12, 20, 13, 16 }, { 30, 21, 13, 17, 18 },
{ 18, 12, 50, 75, 31 }, { 32, 33, 25, 24, 40 }, };
int max = 0;
int row = -1;
int col = -1;
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr[i].length;j++){
if(arr[i][j]>max){
max = arr[i][j];
row = i;
col = j;
}
}
}
System.out.println("最大元素是:"+max+" 位置是 i="+row+" j="+col);
}
}


我的写法是不是也很菜啊,只能想到这,呵呵
安心逍遥 2011-09-22
  • 打赏
  • 举报
回复
其实这个还是要自己多动一下脑子的

学习要自己善于思考

做好之后要看一下还有没有简单的方法

祝楼主好运
softroad 2011-09-22
  • 打赏
  • 举报
回复
lz写的有点复杂了。
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 punbiwee 的回复:]

how to writing programme to sum 1 to 100 by java
[/Quote]
public class Sum {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0 ;
int [] array ;
array = new int [100] ;

for(int i=0; i<=99;i++){
array[i] = i+1;
sum += array[i] ;
}
System.out.println("从1到100的和是: "+sum);


}

}
//我是超级菜鸟 这是我的笨办法
punbiwee 2011-09-22
  • 打赏
  • 举报
回复
how to writing programme to sum 1 to 100 by java
qybao 2011-09-21
  • 打赏
  • 举报
回复
LZ不是问问题吧?
liuyuhua0066 2011-09-21
  • 打赏
  • 举报
回复
接分??

51,397

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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