我正在尝试使用C#准备Turtle图形解决方案。一切工作正常,但由于StackOverflowException而终止于进程终止。我检查了this 和 this 问题是吸气塞特或无限循环。但是我的代码中没有任何这种情况。我是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();
}
}
}
}
}
感谢您提供任何快速帮助。谢谢
答案 0 :(得分:3)
在一种明显的情况下,您最终会无休止地循环。假设您正在输入Moves
方法,而direction
是4:
private static void Moves()
{
switch (direction)
{
case 0:
//Nope
case 1:
//Nope
case 2:
//Nope
case 3:
//Nope
default:
if (direction < 0)
//Nope
else
direction = 4; //Okay, but it already was
Moves(); //And call myself again
代码无法取得进一步的进展,并且调用堆栈中充满了对Moves()
的调用,这些调用永远都不会结束。
我无法提供更正,因为我不了解您的代码打算做什么。使用更清晰的方法名称和描述做什么的XML文档注释将其分解为更小的方法。然后确保代码和注释一致。
我不知道名为Moves
的方法的正确操作是什么。
答案 1 :(得分:0)
Moves中switch语句的默认部分应为:
default:
if (direction < 0)
direction += 4;
else
direction -= 4;
Moves();
break;
因为它的目的是包装方向值,使其始终保持在0-3范围内。