如何在二维数组matrix中查找findNumber的位置?Position类使用疑问
解决二维数组中查找整数位置的问题
嘿,我来帮你理清这个问题~作为编程新手,你在Position类的设计和方法逻辑上踩了几个常见的小坑,我们一步步来修正:
你的代码里的核心问题
- Position类没有存储位置的属性:你想让它代表一个位置,但却没定义
行和列的字段/属性,找到数字后根本没法记录坐标。 - 无限递归实例化:
public Position numberPosition = new Position();这行代码会让创建Position对象时不断自己实例化自己,直接触发栈溢出错误,完全不需要这行。 - 查找逻辑搞反了行和列:
matrix.GetLength(0)是数组的行数,GetLength(1)是列数,但你用y遍历列、x遍历行,还把matrix[y, x]当成了取值,这会导致索引越界或者找不到目标。 - 没有重写ToString方法:直接打印Position对象会输出类的全名,而不是你想要的位置信息。
修正后的完整代码
1. 重构后的Position类
这个版本的Position类专门用来存储位置信息,并且包含查找方法:
class Position { // 存储行、列坐标的属性 public int Row { get; set; } public int Col { get; set; } // 标记是否找到目标数字 public bool IsFound { get; set; } // 重写ToString,让打印时能输出友好的位置信息 public override string ToString() { return IsFound ? $"找到数字啦!位置:行 {Row + 1},列 {Col + 1}" // +1是因为用户习惯从1开始数,不是从0 : "抱歉,没找到这个数字"; } // 查找方法:在当前实例中设置找到的位置 public void FindNumber(int[,] matrix, int findNumber) { int totalRows = matrix.GetLength(0); int totalCols = matrix.GetLength(1); // 正确遍历每一行每一列 for (int row = 0; row < totalRows; row++) { for (int col = 0; col < totalCols; col++) { if (matrix[row, col] == findNumber) { Row = row; Col = col; IsFound = true; return; // 找到第一个匹配就返回,要找所有匹配的话删掉这行,用列表存 } } } // 没找到的话标记为未找到 IsFound = false; } }
2. 修正后的Program类
你的Program类大部分没问题,我加了输入验证避免程序崩溃:
class Program { Random RNG = new Random(); static void Main(string[] args) { Program FindNumber = new Program(); FindNumber.Start(); } void Start() { int[,] matrix = new int[8, 10]; InitMatrixRandom(matrix, 0, 100); DisplayMatrix(matrix); Console.WriteLine("Give the number to be searched: "); // 加输入验证,避免用户输入非整数导致程序崩溃 if (!int.TryParse(Console.ReadLine(), out int findNumber)) { Console.WriteLine("请输入有效的整数!"); Console.ReadKey(); return; } Position numberPosition = new Position(); numberPosition.FindNumber(matrix, findNumber); Console.WriteLine(numberPosition); Console.ReadKey(); } void InitMatrixRandom(int[,] matrix, int min, int max) { for (int row = 0; row < matrix.GetLength(0); row++) { for (int col = 0; col < matrix.GetLength(1); col++) { matrix[row, col] = RNG.Next(min, max); } } } void DisplayMatrix(int[,] matrix) { for (int row = 0; row < matrix.GetLength(0); row++) { for (int col = 0; col < matrix.GetLength(1); col++) { Console.Write(string.Format("{0,3} ", matrix[row, col])); } Console.Write(Environment.NewLine); } } }
额外小提示
- 如果需要查找所有匹配的位置,可以把Position改成存储多个坐标的结构,或者让FindNumber方法返回
List<Position>对象。 - 输入验证是新手容易忽略的点,用
int.TryParse能让程序更健壮。
内容的提问来源于stack exchange,提问作者Leroy de Smet
相关产品推荐
相关产品推荐

