【发布时间】:2012-02-10 20:08:27
【问题描述】:
第一次发贴很抱歉,如果这太长了,但我碰壁了,不知道还能尝试什么。
我正在使用 C# 和 WPF 制作矩阵计算器。
过去一个小时我一直在试图找出我的 Array Iterator 出了什么问题,以查看和编辑 2D NxN 数组中的值。
为了更好地了解我的项目到目前为止需要用户输入大小 n 来制作数组。它将生成一个大小为 0 的 NxN 的 2D int 数组,并从默认位置 (0, 0) 开始。从那里用户可以编辑从左到右,从上到下编辑整个数组的值。
我有 2 个私有全局整数,一个跟踪行位置,一个跟踪列位置并操纵这些数字来编辑数组的该部分。
迭代开始正常 (0, 0) > (0, 1);但是,它不会像从 (0,1) > (0,2) 那样跳到 (1, 1)。我已经无数次地检查了我的 if 逻辑,但找不到我做错的地方。
我还没有测试从右到左、从下到上的遍历,但由于它的逻辑几乎相同,我假设它会遇到我目前遇到的相同问题。
非常感谢,如果有人能指出我的逻辑中存在缺陷的地方,那么我可以继续编写其他部分的代码。
我的代码如下:
private int[,] matrix; //Matrix currently being edited
private int row; //keeps track of current row position and set to 0 when matrix is made
private int col; //Keeps track of current column position and set to 0 when matrix is made
private void previousPos_Click(object sender, RoutedEventArgs e)
{
Console.WriteLine("row " + row + "\r\n col " + col);
if (row < 0 && col < 0)
{
textBlock1.Text = "No previous values to edit";
row = 0;
col = 0;
positionDisplay.Text = "" + col + ", " + row;
}
else if (row < 0 && col < 3)
{
setValue(row, col, valueDisplay.Text);
row = 2;
col -= 1;
displayMatrix(matrix);
positionDisplay.Text = "" + col + ", " + row;
}
else
{
setValue(row, col, valueDisplay.Text);
row -= 1;
displayMatrix(matrix);
positionDisplay.Text = "" + col + ", " + row;
}
}
private void nextPos_Click(object sender, RoutedEventArgs e)
{
Console.WriteLine("row "+row+"\r\ncol "+col);
if (row >= matrix.GetLength(0) && col >= matrix.GetLength(1))
{
textBlock1.Text = "No more values to edit";
row = matrix.GetLength(0) - 1;
col = matrix.GetLength(1) - 1;
positionDisplay.Text = "" + col + ", " + row;
}
else if (row >= matrix.GetLength(0) && col < matrix.GetLength(1))
{
setValue(row, col, valueDisplay.Text);
col += 1;
row = 0;
displayMatrix(matrix);
positionDisplay.Text = "" + col + ", " + row;
}
else
{
setValue(row, col, valueDisplay.Text);
row += 1;
displayMatrix(matrix);
positionDisplay.Text = "" + col + ", " + row;
}
}
public void setValue(int curRow, int curCol, string value)
{
col = curRow;
row = curCol;
try
{
matrix[row, col] = int.Parse(value);
}
catch(Exception)
{
string messageBoxText = "Please input a valid number";
string caption = "Warning";
MessageBoxButton button = MessageBoxButton.OK;
MessageBoxImage icon = MessageBoxImage.Warning;
MessageBox.Show(messageBoxText, caption, button, icon);
}
}
编辑:修正了我看到的一个错字,并愿意根据要求发布更多/其余代码。
【问题讨论】:
标签: c# wpf iterator calculator multidimensional-array