我已经创建了堆栈的私有类成员,但不知道如何从主方法直接或间接访问它,尽管我没有使用任何对象。程序执行排序方法时,直接自动修改私有成员“stk[]”。
这是从 main 方法调用排序选项时间接从 main 方法修改私有 String stk[] 的代码:
import java.io.*;
class Stack
{
private String stk[];
private int tos;
private int size;
Stack()
{
size=5;
stk=new String[size];
tos=-1;
}
Stack(int sz)
{
size=sz;
stk=new String[size];
tos=-1;
}
boolean push(String s)
{
if(tos==size-1) return false;
stk[++tos]=s;
return true;
}
String pop()
{
if(tos<0) return "Stack Underflow";
return stk[tos--];
}
String[] display()//array type function to return an array called "stk"
{
return stk;
}
int returnSize()
{
return tos;
}
}
class myStack
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Stack S=new Stack();
int opt=-1;
while(opt!=6)
{
System.out.println("\n\n\n");
System.out.println("[1] - Create Stack");
System.out.println("[2] - Push");
System.out.println("[3] - Pop");
System.out.println("[4] - Display");
System.out.println("[5] - Display List In Ascending Order");
System.out.println("[6] - Exit");
System.out.print("Option: ");
opt=Integer.parseInt(br.readLine());
if(opt==1)
{
System.out.print("\n\nEnter the size of stack: ");
int size=Integer.parseInt(br.readLine());
S=new Stack(size);
System.out.print("\nStack Created...");
}
else if(opt==2)
{
System.out.print("\n\nEnter String: ");
String s=br.readLine();
if(S.push(s))
System.out.print("\nSuccessfull...");
else
System.out.print("\nStack Overflow...");
}
else if(opt==3)
{
System.out.print("\nItem Deleted: "+S.pop());
}
else if(opt==4)
{
int sz=S.returnSize();
System.out.print("\n\n\nStack Contains: "+(sz+1)+" Item(s)\n");
String st[]=S.display();
while(sz>=0)
{
System.out.println(st[sz]);
sz--;
}
}
else if(opt==5)
{
int s=S.returnSize();
String stc[]=S.display();
for(int i=0;i<=s;i++)
{
for(int j=i+1;j<=s;j++)
{
if(stc[j].compareTo(stc[i])<0)
{
String t=stc[i];
stc[i]=stc[j];
stc[j]=t;
}
}
System.out.println(stc[i]);
}
}
else if(opt>6)
{
System.out.print("\nPress 6 To Exit....");
}
}
}
}