我在wpf做了一个河内的塔。我希望它有一个关于如何使用给定数量的磁盘解决难题的动画。但是当我单击“解决”按钮时,它会出现错误"类型为“System.StackOverflowException'”的未处理异常。发生在TowerOfHanoi.exe"
下面是代码:
private void SolveTower(int diskNumber, Needle origin, Needle tempDest, Needle destination)
{
diskNumber = diskCounter;
if (diskNumber == 1)
{
bgWorker.ReportProgress(0, new Solution(origin, destination)); // move this disk from needle1 to needle3
System.Threading.Thread.Sleep(100);
}
else
{
SolveTower(diskNumber - 1, origin, tempDest, destination); // move n-1 disks from needle1 to needle2
bgWorker.ReportProgress(0, new Solution(origin, destination)); // move the last disk from needle1 to needle3
System.Threading.Thread.Sleep(100);
SolveTower(diskNumber - 1, tempDest, destination, origin); // move n-1 disks from needle2 to needle3
}
}
diskCounter是面板/针具有的磁盘数。我只是不知道如何重新安排它。
这是在面板/针中添加磁盘的代码:
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
Rectangle disk = new Rectangle();
disk.Height = 25;
disk.Stroke = Brushes.BlueViolet;
disk.RadiusX = 7;
disk.RadiusY = 7;
RadialGradientBrush rgBrush = new RadialGradientBrush();
GradientStopCollection gsc = new GradientStopCollection();
gsc.Add(new GradientStop(Colors.AliceBlue, 0));
gsc.Add(new GradientStop(Colors.BlueViolet, 1));
rgBrush.GradientStops = gsc;
rgBrush.GradientOrigin = new Point(0.1, 0.9);
rgBrush.RadiusX = 1;
rgBrush.RadiusY = 1;
disk.Fill = rgBrush;
disk.MouseLeftButtonDown += disk_MouseLeftButtonDown;
if (needle1.Children.Count < 10)
{
needle1.AddDisk(disk);
btnSolve.IsEnabled = true;
btnStart.IsEnabled = true;
}
else
{
MessageBox.Show("Maximum of 10 disks only");
}
diskCounter = needle1.Children.Count;
}
答案 0 :(得分:2)
如果diskCounter
小于1,就会发生这种情况。由于您在方法(diskNumber
)中收到了第一行中覆盖的参数,因此我没有真正得到逻辑。< / p>
我认为这是导致问题的原因。建议:检查输入参数是否符合预期范围,如下所示:
Debug.Assert(diskCounter > 0, "Disk counter should be more than 0");
现在,当你把它放在方法的第一行时,你会看到在调试时会收到警告,告诉你发生了意想不到的事情。