嘿所以我是一个初学者,我正在尝试在Visual Studio中制作一个控制台时钟程序。它可以工作,但是大约2个小时后,由于时钟在无限循环上运行,它会抛出堆栈溢出错误。这是我的代码 -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static string hourInput;
static string minuteInput;
static string yearInput;
static string dayInput;
static string monthInput;
static int saveMonth;
static int saveYear;
static int saveDay;
static int saveSeconds;
static int saveMinutes;
static int saveHours;
static void Main(string[] args)
{
Console.WriteLine("Enter the current hour");
hourInput = (Console.ReadLine());
saveHours = Int32.Parse(hourInput);
Console.WriteLine("Enter the current minute");
minuteInput = (Console.ReadLine());
saveMinutes = Int32.Parse(minuteInput);
Console.WriteLine("Enter the current day");
dayInput = (Console.ReadLine());
saveDay = Int32.Parse(dayInput);
Console.WriteLine("Enter the current month in numerical form");
monthInput = (Console.ReadLine());
saveMonth = Int32.Parse(minuteInput);
Console.WriteLine("Enter the current year");
yearInput = (Console.ReadLine());
saveYear = Int32.Parse(yearInput);
Update();
}
static void Update()
{
Counter();
}
static void Counter()
{
int days = 1;
int minutes = 0;
int hours = 1;
int Seconds = 0;
int months = 1;
int years = 2015;
bool dayOver = false;
Seconds = saveSeconds;
minutes = saveMinutes;
if (saveHours > hours)
{
hours = saveHours;
}
if (saveYear > years)
{
years = saveYear;
}
if (saveMonth > months)
{
months = saveMonth;
}
if (saveDay > days)
{
days = saveDay;
}
Seconds++;
if (Seconds == 60)
{
minutes++;
Seconds = 0;
}
if (minutes == 60)
{
hours++;
minutes = 0;
}
if (hours > 12)
{
if (dayOver == true)
{
days++;
dayOver = false;
}
else
{
dayOver = true;
}
hours = 1;
}
Console.Clear();
Console.WriteLine(days + ":" + hours + ":" + minutes + ":" + Seconds);
saveSeconds = Seconds;
saveMinutes = minutes;
saveHours = hours;
System.Threading.Thread.Sleep(1000);
Update();
}
}
}
那么有没有办法在不抛出堆栈溢出的情况下运行无限循环?请记住,我是一个开始编码器,所以它不能太复杂。我知道还有其他方法可以执行时钟程序,但这是我想要的方式。
答案 0 :(得分:3)
您正在获取StackOverflow,因为您递归调用方法。
每次调用方法时,它都会被推送到调用堆栈。
如果使用while
循环,调用堆栈上存在的唯一方法(我们关心)将是包含while循环的方法,因此没有堆栈溢出。