问题描述:
请找出4*5矩阵中值最小与最大元素,并分别输出其值及所在的行号和列号
代码如下
import java.util.*;
public class Exercise5_2 {
public static void main(String[] args) {
Scanner buf = new Scanner (System.in);
int [][] nums=new int [4][5];
int i=0,j=0,min,max,row1=0,row2=0,col1=0,col2=0;
System.out.print("输入一个四行五列的矩阵:");
System.out.println();
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
nums[i][j]=buf.nextInt();
}
}
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
System.out.print(" "+nums[i][j]);
}
System.out.println();
}
min = Integer.MAX_VALUE;
max = Integer.MIN_VALUE;
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
if(nums[i][j]<min)
{
min=nums[i][j];
row1=i;
col1=j;
}
if(nums[i][j]>max)
{
max=nums[i][j];
row2=i;
col2=j;
}
}
}
System.out.print("最小数是"+min);
System.out.println(",在【"+(row1+1)+"】行【"+(col1+1)+"】列");
System.out.print("最大数是"+max);
System.out.println(",在【"+(row2+1)+"】行【"+(col2+1)+"】列");
}
}
示例
输入一个四行五列的矩阵:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
-1 -5 -8 5 3
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
-1 -5 -8 5 3
最小数是-8,在【4】行【3】列
最大数是15,在【3】行【5】列
总结
如果你是学过C语言的,将所想的改成Java语言规则即可,本题不涉及面向对象