The following Java program uses the data structure Stack to store data and runs
ID: 3846942 • Letter: T
Question
The following Java program uses the data structure Stack to store data and runs without any error. Write the output produced by the program run.
import java.util.Stack;
public class StackTest
{
public static void main(String [] args)
{
// name of courses in an array
String [ ] courses= {“Java”,”C++”,”Pascal”,”COBOL”};
// creating courses Stack and taking the courses from courses array and
// placing them into the course Stack
Stack <String> coursesStack =new Stack<>();
for(int i=0;i< courses.length;i++) coursesStack.push(courses [i]);
// creating completed stack, take the courses from courses- stack ,
// one by one, and place them in completed stack
Stack <String> completedStack =new Stack <String>(); while(coursesStack.size()>0) completedStack.push(coursesStack.pop());
while(completedStack.size()>0)
System.out.println(completedStack.pop));
}
}
Explanation / Answer
OUTPUT is given at the end of the program
one error is there
"( )" parenthesis is missing in the line
System.out.println(completedStack.pop)); to be written as
System.out.println(completedStack.pop());
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.Stack;
public class StackTest
{
public static void main(String [] args)
{
// name of courses in an array
String[] courses= {"Java","C++","Pascal","COBOL"};
// creating courses Stack and taking the courses from courses array and
// placing them into the course Stack
Stack <String> coursesStack =new Stack<>();
for(int i=0;i< courses.length;i++) coursesStack.push(courses [i]);
// creating completed stack, take the courses from courses- stack ,
// one by one, and place them in completed stack
Stack <String> completedStack =new Stack <String>(); while(coursesStack.size()>0) completedStack.push(coursesStack.pop());
while(completedStack.size()>0)
System.out.println(completedStack.pop());
}
}
OUTPUT
Java
C++
Pascal
COBOL