本文介绍了在公共类中声明变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我正在尝试使用C#实现堆栈,但是我无法声明变量,我尝试了一个代码,但是我收到一个错误,说名字''顶部' 在当前上下文中不存在。我打开了一个公共静态类,并在那里声明了所有变量,但它似乎没有工作,任何人都可以帮助我。 我甚至试过Data.top ......它不起作用 这是我试过的代码Hi, I am trying to implement a stack using C#,but I am not able to declare the variables, I tried a code but I get an error saying "The name ''top'' does not exist in the current context".I opened a public static class and declared all the variables in there,but it doesn''t seem to be working,can anyone help me out.I even tried Data.top...it doesnt workThis is the code that I triedusing System;using System.Collections.Generic;using System.Linq;using System.Text;namespace _2{ class Program { public static class Data { public const int MAX = 5;//Defining the stack value public static int top = -1;//Stack is empty public int[] stack = new int[MAX];//Declare an array called stack } public static void push() { int element; if (top ==MAX - 1) { Console.WriteLine("Stack Overflow"); return; } else { Console.WriteLine("enter the number to be pushed"); element = int.Parse(Console.ReadLine()); stack[++top] = element; Console.WriteLine("The number is pushed successfully", element); } return; } public static void pop() { int y; if (top == -1) { Console.WriteLine("Stack underflow"); return; } else { y = stack[top]; stack[top--] = 0; Console.WriteLine("The element has been popped", y); return; } } public static void display() { int i; if (top == -1) { Console.WriteLine("Stack is empty"); return; } else { Console.WriteLine("Elements are :\n"); for (i = 0; i <= top; i++) { Console.WriteLine("%d\n", stack[i]); } return; } } static void Main() { int ch; do { Console.WriteLine("Enter Your choice \n1.Push\n2.Pop \n3.Display \n4.Exit"); ch = int.Parse(Console.ReadLine()); switch (ch) { case 1: push(); break; case 2: pop(); break; case 3: display(); break; case 4: break; default: Console.WriteLine("Invalid Selection"); break; } } while (ch != 4); } } }推荐答案if (Data.top == Data.MAX - 1) 而不是instead of引用: if(top == MAX - 1)if (top ==MAX - 1) 顺便说一句,因为 Data.stack 不是 static ,所以没有实例就无法访问它数据类。By the way, since Data.stack is not static, you cannot access it without an instance of the Data class.public static class Data { public const int MAX = 5;//Defining the stack value public static int top = -1;//Stack is empty public int[] stack = new int[MAX];//Declare an array called stack }这是Data类的总和,因为close括号结束了定义。 br /> 你需要push,pop和display方法在Data类中,所以在Main方法下面移动关闭的大括号。This is the totality of your Data class, because the close bracket ends the definition.You need the push, pop and display methods to be within the Data class, so move the close curly bracket below the Main method. 这篇关于在公共类中声明变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
05-27 23:51
查看更多