我是C#的新手,可以通过实践学习。因此,我正在参考C语言中的Stack程序在C#中实现Stack程序。但是我面临无限切换循环的问题。我已经尝试发表评论,但是我一直在努力寻找无限循环的原因。所以我在SO来获得一些知识和帮助。请帮助了解此代码出了什么问题。
using System;
public class stack
{
public const int MAX = 5;
public static void Main()
{
int[] st = new int[5];
int top = -1;
int a;
void push()
{
Console.WriteLine("ENTER ELEMENT TO PUSH\n");
a = Convert.ToInt32(Console.ReadLine());
if (top == MAX)
{
Console.WriteLine("STACK OVERFLOW");
}
else if(top == -1)
{
top = 1;
st[top] = a;
}
else
{
top = top + 1;
st[top] = a;
}
}
void pop()
{
if (top == -1)
{
Console.WriteLine("STACK UNDERFLOW");
}
else if(top == MAX)
{
top = top - 1;
}
else
{
top = top - 1;
}
}
void Display()
{
Console.WriteLine("ELEMENTS INSIDE STACK ARE : : \n");
foreach(int stack in st)
{
Console.WriteLine(stack);
Console.WriteLine("\n");
}
}
while(true)
{
int ch;
Console.WriteLine("ENTER YOUR CHOICE : :\n");
Console.WriteLine("1.PUSH\n2.POP\n3.DISPLAY\n");
ch = Convert.ToInt32(Console.ReadLine());
switch (ch)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
Display();
break;
}
default:
{
Console.WriteLine("WRONG CHOICE\n");
break;
}
}
}
}
}
在C中工作的东西,在C#中完全不一样,因为C是面向[[procedure的语言,而C#是面向对象的语言。因此,在C#中,我们应该使用类和对象来实现此目的。 classes和objects,什么是静态,访问说明符的概念对于在C#中正确重写此代码很重要。
无限切换循环的问题:
无限循环不是因为switch
,而是因为while (true)
。 while循环将一直执行直到其条件语句为真,并且您直接将true
用作永远不会改变的条件语句,因此将导致无限循环。切记切勿使用while (true)
。要记住的一件事是数组索引从0而不是1开始。因此,您的top = 1
应该是top = 0
我对您的代码进行了很少的更改以使其可运行。请看看并观察更改,主要使用单独的类和第4个选项退出应用程序。using System;
using System.Globalization;
using System.Collections.Generic;
using System.Data;
public class Program
{
public static void Main()
{
while ( true )
{
int ch;
Console.WriteLine("ENTER YOUR CHOICE : :\n");
Console.WriteLine("1.PUSH\n2.POP\n3.DISPLAY\n4.Exit");
ch = Convert.ToInt32(Console.ReadLine());
switch (ch)
{
case 1:
{
Stack.push();
break;
}
case 2:
{
Stack.pop();
break;
}
case 3:
{
Stack.Display();
break;
}
case 4:
{
Environment.Exit(0);
break;
}
default:
{
Console.WriteLine("WRONG CHOICE\n");
break;
}
}
}
}
}
public class Stack
{
public const int MAX = 5;
public static int a;
public static int[] st = new int[5];
public static int top = -1;
public static void push()
{
if (top + 1 == MAX)
{
Console.WriteLine("STACK OVERFLOW");
return;
}
Console.WriteLine("ENTER ELEMENT TO PUSH\n");
a = Convert.ToInt32(Console.ReadLine());
if (top == -1)
{
top = 0;
st[top] = a;
}
else
{
top = top + 1;
st[top] = a;
}
}
public static void pop()
{
if (top == -1)
{
Console.WriteLine("STACK UNDERFLOW");
}
else if (top == MAX)
{
top = top - 1;
}
else
{
top = top - 1;
}
}
public static void Display()
{
Console.WriteLine("ELEMENTS INSIDE STACK ARE : : \n");
foreach (int stack in st)
{
Console.WriteLine(stack);
Console.WriteLine("\n");
}
}
}