【发布时间】:2019-01-04 13:51:21
【问题描述】:
我正在尝试用 C# 准备 Turtle 图形解决方案。一切正常,但由于 StackOverflowException 而以 Process Terminated 结束。我检查了this 和 this 问题在于getter setter或无限循环。但是我的代码中没有任何这种情况。我是 C# 的新手。 下面是我的代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TurtleGraphics
{
class Program
{/**
* Directions: 0 right, 1 down, 2 left, 3 up
*/
private static short direction = 0;
private static bool penDown;
private static int turtleX = 0, turtleY = 0;
private static int[,] floor = new int[20, 20];
public static void Main(String[] args)
{
initFloor(floor);
//Scanner in = new Scanner(System.in);
printMenu();
int nextCommand = int.Parse(Console.ReadLine());
while (nextCommand != 9)
{
switch (nextCommand)
{
case 1:
penDown = false;
break;
case 2:
penDown = true;
break;
case 3:
direction++;
break;
case 4:
direction--;
break;
case 5:
Console.WriteLine("How many steps do you want to move?");
int move = int.Parse(Console.ReadLine());
if (move <= 10)
while (--move != 0)
Moves();
break;
case 6:
printArray();
break;
default:
Console.WriteLine("Unknow command, please try again:\n");
break;
}
Moves();
Console.WriteLine("What's next?");
nextCommand = int.Parse(Console.ReadLine());
}
}
private static void initFloor(int[,] floor)
{
for (int i = 0; i < floor.GetLength(0); i++)
{
for (int j = 0; j < floor.GetLength(1); j++)
{
floor[i,j] = 0;
}
}
}
private static void printMenu()
{
Console.WriteLine("Commands List:\n\n\t1 Pen up\n"
+ "\t2 Pen down\n"
+ "\t3 Turn right\n"
+ "\t4 Turn left\n"
+ "\t5 to 10 Move forward 10 spaces (replace 10 for a different number of spaces)\n"
+ "\t6 Display the 20-by-20 array\n"
+ "\t9 End of data (sentinel)Please enter a command number:\n");
}
private static void printArray()
{
for (int i = 0; i < floor.GetLength(0); i++)
{
for (int j = 0; j < floor.GetLength(1); j++)
{
// Console.WriteLine(floor[i, j]);
// Console.WriteLine(" ");
if (floor[i, j] == 0)
Console.Write(".");
else if (floor[i, j] == 1)
Console.Write("*");
else if (floor[i, j] == 2)
Console.Write("T");
}
Console.WriteLine();
}
}
private static void Moves()
{
switch (direction)
{
case 0:
turtleX++;
break;
case 1:
turtleY++;
break;
case 2:
turtleX--;
break;
case 3:
turtleY--;
break;
default:
if (direction < 0)
direction = 3;
else
direction = 4;
Moves();
break;
}
if (penDown)
{
if (turtleX < 20 && turtleY < 20)
floor[turtleX, turtleY] = 1;
else
{
direction -= 2;
Moves();
}
}
}
}
}
感谢任何快速帮助。谢谢
【问题讨论】:
-
通常任何“溢出”异常都意味着发生了无限循环。尝试调试以找出循环过多的地方(比如数百万次......)
-
还要检查主循环中的案例 5 - 如果运算符输入 0,则移动将小于 10,您的 while 循环会将其递减为 -1 并且不会为零 - 所以你最终会进行 40 亿次移动,直到数字再次归零。
-
如果方向小于零则设置为 3 是不正确的:乌龟可以转动任意步数,因此方向可以是任意负值,为了找到正确的方向,您必须一次添加 4 个,如下面的回答所示。
标签: c# recursion stack-overflow turtle-graphics