1. Java的二维数组在实际应用中使用是非常广泛的。下面示例演示使用二维数组实现打印一组数据中的最大值和最小值。
public class MutiArray { int theValues[][]={ {12,23,33,56,26}, {9,87,68,55,26}, {36,88,98,43,19}, {25,16,8,37,99} }; //求二维数组中最小元素的方法 public int minimum() { int lowTheValue=theValues[0][0]; for (int row=0;row<theValues.length;row++) { for(int column=0;column<theValues[row].length;column++) { if (lowTheValue > theValues[row][column]) { lowTheValue=theValues[row][column]; } } } return lowTheValue; } //求二维数组中最大元素的方法 public int maximum() { int highTheValue=theValues[0][0]; for (int row=0;row<theValues.length;row++) { for(int column=0;column<theValues[row].length;column++) { if (highTheValue < theValues[row][column]) { highTheValue=theValues[row][column]; } } } return highTheValue; } //主方法 public static void main(String[] args) { MutiArray item = new MutiArray(); System.out.println("数组中的最小元素是: " + item.minimum()); System.out.println("数组中的最大元素是: " + item.maximum()); } }
2. 现在再看看C#中处理相同值的二维数组,其代码如下所示:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleAppArray { public class MutiArray { public static int[,] mutiArray = new int[4,5]{ {12,23,33,56,26}, {9,87,68,55,26}, {36,88,98,43,19}, {25,16,8,37,99} }; //定义二维数组并初始化 //求二维数组中最小元素的方法 public static int minimum() { int lowMutiArray = mutiArray[0, 0]; for(int row=0;row <mutiArray.GetLength(0);row++) { for (int column = 0; column < mutiArray.GetLength(1); column++) { if(lowMutiArray > mutiArray[row, column]) { lowMutiArray = mutiArray[row, column]; } } } return lowMutiArray; } //求二维数组中最大元素的方法 public static int maximum() { int highMutiArray = mutiArray[0, 0]; for(int row = 0; row < mutiArray.GetLength(0); row++) { for(int column = 0;column < mutiArray.GetLength(1); column++) { if(highMutiArray < mutiArray[row, column]) { highMutiArray = mutiArray[row, column]; } } } return highMutiArray; } } class Program { static void Main(string[] args) { //遍历二维数组 foreach(int item in MutiArray.mutiArray) { Console.Write(item + ","); } Console.WriteLine(); Console.WriteLine("二维数组中最小的元素是:" + MutiArray.minimum()); Console.WriteLine("二维数组中最大的元素是:" + MutiArray.maximum()); Console.ReadLine(); } } }
执行结果如下图所示:
原文:http://www.cnblogs.com/lxh168/p/7748531.html