In: Computer Science
how can I save a character stack to a string and then save that string into a new string arraylist in java?
so if the character stack is h, e, l, l, o
i want it to save "hello" to a string and then put that string into
an array list.
import java.io.*;
class String_Stack
{
int N, top=-1;
char A[];
String_Stack(int x)
{
N=x;
A= new char [N];
}
void Push(char n)
{
if(top==N-1)
System.out.println("Stack Overflow");
else
A[++top]= n;
}
char Pop()
{ char m;
if(top==-1)
System.out.println("Stack Underflow");
else
{ m= A[top]; --top;
}
return m;
}
void display()
{
if(top==-1)
System.out.println("Stack underflow");
else {
for(int i=0; i<=top; i++)
System.out.println(A[i]); }
}
public static void main(String args[])throws
IOException
{
BufferedReader br= new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the
length of the stack: ");
int n=
Integer.parseInt(br.readLine());
String_Stack obj= new
String_Stack(n);
do{
System.out.println("1. Push
character.");
System.out.println("2. Pop
character.");
System.out.println("3. Display
Stack.");
System.out.println("Enter your
choice: ");
int ch=
Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
System.out.println("Enter the character");
char c= br.readLine();
obj.Push(c);
break;
case 2:
char m=obj.Pop();
System.out.println("The character popped is:
"+m);
break;
case 3:
obj.display();
break;
default:
System.out.println("Invalid Entry");
}
System.out.println("Do you wish to
continue(Y/N)?");
char ch2= br.readLine();
}
while(ch2=='Y' || ch2=='y');
//exits from while considering that
the final string has been stored
String S="";
for(int i=top; i>=0; i--)//since
the word is stored in reverse order in the stack
{
S= S+A[i];
}
ArrayList al=new
ArrayList();
al.add(S);
}
}