logo
down
shadow

How to print out the whole contents of a stack?


How to print out the whole contents of a stack?

By : Sunakshi Gujral
Date : November 22 2020, 02:59 PM
To fix this issue If it's java.util.Stack you're talking about, it has an iterator() method, which you can use to iterate over its elements, for example:
code :
Iterator<Integer> iterator = stack.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}
ListIterator<Integer> listIterator = stack.listIterator(stack.size());
while (listIterator.hasPrevious()) {
    System.out.println(listIterator.previous());
}


Share : facebook icon twitter icon
How can I print out the contents of std::stack and return its size?

How can I print out the contents of std::stack and return its size?


By : abelfinch
Date : March 29 2020, 07:55 AM
To fix this issue You could make a copy of the stack and pop items one-by-one to dump them:
code :
#include <iostream>
#include <stack>
#include <string>

int main(int argc, const char *argv[])
{
    std::stack<int> stack;
    stack.push(1); 
    stack.push(3); 
    stack.push(7); 
    stack.push(19); 

    for (std::stack<int> dump = stack; !dump.empty(); dump.pop())
        std::cout << dump.top() << '\n';

    std::cout << "(" << stack.size() << " elements)\n";

    return 0;
}
19
7
3
1
(4 elements)
How to print the contents of an array without creating anything on the stack?

How to print the contents of an array without creating anything on the stack?


By : Narendra Singh
Date : March 29 2020, 07:55 AM
wish helps you I beleive, that this question was intended more to check your understanding of internal program working (stack usage, allocation/deallocation, etc). Lets consider your question:
Java array stack, printing contents of stack from top to bottom

Java array stack, printing contents of stack from top to bottom


By : Kimosabi77
Date : March 29 2020, 07:55 AM
I wish this help you I'm relatively new to programming and can't sort this one out. I have an array stack that I have just set up. I'm trying to create a toString() method that returns the contents of the array listed from top to bottom of the stack. , replace your toString method with :
code :
 public String toString(){
     String result = "";
     for (int scan =top-1 ; scan >= 0; scan--)
         result = result + stack[scan].toString() + "\n";
     return result;
 }
How to print contents in stack to a file

How to print contents in stack to a file


By : ravi
Date : March 29 2020, 07:55 AM
seems to work fine You create a PrintWriter in method main() of class PostFixEval, so rather than pass the name of the output file to methods parseFromFile() and translate(), pass the PrintWriter and don't create more new PrintWriter objects in those methods.
However that is not your problem. From the code you posted, your problem is in method translate() with this line of your code
code :
else if (Character.isLetter(expression.charAt(i))) {
import java.io.*;

public class PostFixEval {
    public static void main(String[] args) throws StackException, IOException {
        File fin = new File(args[0]);
        boolean fileExist = fin.exists();

        File fout = new File(args[1]);
        try (PrintWriter pw = new PrintWriter(new FileWriter(fout))) {
            if (fileExist == true) {
                pw.println("\n" + "\t\t\t\t" + "--- EVALUATION BEGINS ---");
                parseFromFile(args[0], pw);
            }
            else {
                translate(args[0], pw);
            }
            pw.println("\t\t\t\t" + "--- EVALUATION COMLETE ---" + "\n");
        }
    }

    public static void parseFromFile(String input, PrintWriter pw) throws IOException {
        String line = null;
        int lineCounter = 0;

        try {
            BufferedReader br = new BufferedReader(new FileReader(input));

            try {
                while ((line = br.readLine()) != null) {
                    lineCounter++;
                    pw.println("EXAMPLE " + lineCounter + ": ");
                    pw.println("Postfix Expression: " + line);

                    try {
                        translate(line, pw);
                    }
                    catch (StackException e) {
                        pw.println("ERROR: Invalid expression encountered: exiting");
                        pw.println(e);
                    }
                    pw.println("\n");
                }
                br.close();
            }
            catch (java.io.IOException e) {
                pw.println("EOF encountered");
            }

        }
        catch (java.io.FileNotFoundException e) {
            pw.println("Cannot find file: " + input);
        }
    }

    private static boolean isOperator(String operator) {
        switch (operator) {
            case "+":
            case "-":
            case "*":
            case "/":
            case "$":
                return true;
            default:
                return false;
        }
    }

    private static String instruction(String oper) {
        switch (oper) {
            case "+":
                return "AD";
            case "-":
                return "SB";
            case "*":
                return "ML";
            case "/":
                return "DV";
            case "$":
                return "EX";
            default:
                return "N/A";
        }
    }

    public static void translate(String expression, PrintWriter pw) throws StackException, IOException {
        Stack variables = new Stack();
        int tempNum = 1;
        String arg1;
        String arg2;
        String command;

        pw.println("Instructions in the Register:");
        if (expression == null) {
            throw new IllegalArgumentException("null expression");
        }
        expression = expression.trim();
        if (expression.length() == 0) {
            throw new StackException("EMPTY STACK");
        }
        int limit = expression.length() - 1;
        for (int i = 0; i < limit; i++) {
            String argument = expression.substring(i, i + 1);
            // if operator, pop arguements and evaluate
            if (isOperator(argument)) {
                if (variables.isEmpty()) {
                    throw new StackException("EMPTY STACK");
                }
                command = instruction(expression.substring(i, i + 1));
                try {
                    arg1 = variables.pop();
                }
                catch (StackException e) {
                    throw new StackException("EMPTY STACK ON ARG1");
                }

                try {
                    arg2 = variables.pop();
                }
                catch (StackException e) {
                    throw new StackException("EMPTY STACK ON ARG2");
                }

                variables.push("TEMP" + tempNum);
                pw.println("LD " + arg2);
                pw.println(command + " " + arg1);
                pw.println("ST " + "TEMP" + tempNum);
                tempNum++;
            }
            else if (Character.isLetter(expression.charAt(i))) {
                variables.push(argument);
                // if variab.l+ng(i, i+1));
            }
            else if (Character.isWhitespace(expression.charAt(i))) {
                // Ignore whitespace
                continue;
            }
            else {
                throw new StackException(
                        "Unrecognized characterr: " + expression.charAt(i) + " at position: " + i);
            }
        }

        if (variables.isEmpty() == false) {
            while (variables.isEmpty() == false) {
                if (variables.pop().startsWith("TEMP") == false) {
                    throw new StackException("Leftover variables after evaluation.");
                }
            }
        }
    }
}
                --- EVALUATION BEGINS ---
EXAMPLE 1: 
Postfix Expression: AB+C-
Instructions in the Register:
LD A
AD B
ST TEMP1
ERROR: Invalid expression encountered: exiting
gnrltsts.StackException: Leftover variables after evaluation.


EXAMPLE 2: 
Postfix Expression: ABC+-
Instructions in the Register:
LD B
AD C
ST TEMP1
ERROR: Invalid expression encountered: exiting
gnrltsts.StackException: Leftover variables after evaluation.


EXAMPLE 3: 
Postfix Expression: AB-C+DEF-+$
Instructions in the Register:
LD A
SB B
ST TEMP1
LD TEMP1
AD C
ST TEMP2
LD E
SB F
ST TEMP3
LD D
AD TEMP3
ST TEMP4


EXAMPLE 4: 
Postfix Expression: ABCDE-+$*EF*-
Instructions in the Register:
LD D
SB E
ST TEMP1
LD C
AD TEMP1
ST TEMP2
LD B
EX TEMP2
ST TEMP3
LD A
ML TEMP3
ST TEMP4
LD E
ML F
ST TEMP5


EXAMPLE 5: 
Postfix Expression: ABC+*CBA-+*
Instructions in the Register:
LD B
AD C
ST TEMP1
LD A
ML TEMP1
ST TEMP2
LD B
SB A
ST TEMP3
LD C
AD TEMP3
ST TEMP4


EXAMPLE 6: 
Postfix Expression: ABC+/CBA*+
Instructions in the Register:
LD B
AD C
ST TEMP1
LD A
DV TEMP1
ST TEMP2
LD B
ML A
ST TEMP3
ERROR: Invalid expression encountered: exiting
gnrltsts.StackException: Leftover variables after evaluation.


EXAMPLE 7: 
Postfix Expression: AB-*CBA+-*
Instructions in the Register:
LD A
SB B
ST TEMP1
ERROR: Invalid expression encountered: exiting
gnrltsts.StackException: EMPTY STACK ON ARG2


EXAMPLE 8: 
Postfix Expression: ABC-/BA-+/
Instructions in the Register:
LD B
SB C
ST TEMP1
LD A
DV TEMP1
ST TEMP2
LD B
SB A
ST TEMP3
LD TEMP2
AD TEMP3
ST TEMP4


EXAMPLE 9: 
Postfix Expression: ABC+$CBA-+*
Instructions in the Register:
LD B
AD C
ST TEMP1
LD A
EX TEMP1
ST TEMP2
LD B
SB A
ST TEMP3
LD C
AD TEMP3
ST TEMP4


EXAMPLE 10: 
Postfix Expression: AB0+/CBA+-/
Instructions in the Register:
ERROR: Invalid expression encountered: exiting
gnrltsts.StackException: Unrecognized characterr: 0 at position: 2


EXAMPLE 11: 
Postfix Expression: ABC*+DE-/
Instructions in the Register:
LD B
ML C
ST TEMP1
LD A
AD TEMP1
ST TEMP2
LD D
SB E
ST TEMP3


EXAMPLE 12: 
Postfix Expression: AB#CD@EF
Instructions in the Register:
ERROR: Invalid expression encountered: exiting
gnrltsts.StackException: Unrecognized characterr: # at position: 2


                --- EVALUATION COMLETE ---
How can I print the contents of stack in C program?

How can I print the contents of stack in C program?


By : Rudra
Date : March 29 2020, 07:55 AM
this one helps. If your utilising a GNU system, you may be able to use GNU's extension to the C library for dealing backtraces, see here.
Related Posts Related Posts :
  • How to query using objectify in Google App Engine app
  • List value is printing address instead of value
  • StringUtils.isBlank return false for null Strings
  • Sent parameter through PATCH android
  • i am not able to clear the code below given using throwable concept in java
  • How to get System time instead of Server time in java?
  • How to push json data into an arrya object in MONGO DB by java
  • Saving RelationshipEntity not working
  • Error on "instanceOf" when checking a subClass
  • Java - Splitting a image into 4 images
  • "Pinging" a server in Java
  • RoboGuice Proguard CreationException
  • Android Array list returns Null after adding values
  • Jar Executable what am I doing wrong?
  • How do I mitigate Connection leak triggered for connection com.mysql.jdbc.JDBC4Connection@11d08960,
  • How do i iterate values from a 2d array using conditions
  • Hide Button in CustomPagerAdapter
  • Java GC: does it ever make sense to call super.finalize() in a class that only extends Object?
  • 64bit HashMap in Java
  • Hibernate wildcard query on two columns
  • Want to Generate Auto Login Program Using Java
  • Spring security Oauth 2 with ajax login and form login
  • Parse findInBackground doesn't add to global arraylist?
  • Remove random item from ArrayList
  • in SpringMVC getMessage from i18n properties in a function outside the controller
  • How do I add JCheckBox next to each name that has been entered into an arraylist from a JTextField?
  • Return node ID along with complete node
  • InvocationTargetException. Cannot cast class X to class X. When invoked in Scala Imain through spark-submit
  • how to print elements of a 1D array into a N x N box
  • How to map csv file to pojo class in java
  • How, in Java, to encode default vhost %2F in URL/URI so it doesn't get changed to slash and fail to work
  • Tomcat 5.5 https configuration in Windows Server 2008 64bit
  • Enabling FIPS 140-2 compliance mode in MULE ESB
  • How to pass String PackageName to PkgName under parseXML() and run XMLParser class as a new activity when click on list
  • Error while creating spring -hibernate configuration file
  • Hand off control between java threads
  • NoClassDefFoundError: scala/collection/Seq
  • Getting stack overflow error on one machine but not the other on the same code
  • How can I loop AsyncAjaxRequest in GWT?
  • Failed to find provider info for urbanairship.provider
  • Android ListView Adapter Crash issue/Duplicates
  • Displaying Splash screen only once on user preference
  • Loop List<WebElement> doesn't stop despite no more WebElements
  • Check if pattern exists in a String
  • Swing - Key Problems (Arrow Keys, Tab, etc.) in GUIs with TextComponents
  • Why the solution for binary search tree validity is not working?
  • Double encrypting 2048 RSA?
  • create junit test for runnable class
  • Unable to read and sort information from a text file in Java
  • My device isn't getting detected in android studio (driver issue)
  • Representing a Graph in Java
  • How to XML mapping using jxls
  • Quick Sort stackoverflow error for large arrays
  • Parsing Apache Tika XML Output returns Unknown Tag
  • java simple UI loop, can't find bug
  • how to use greater than and less than in a single if statement in java
  • Error:(27, 13) Failed to resolve: com.antonyt.infiniteviewpager:library:1.0.0
  • Gradle dependencies on source set of different projects
  • Session Scope in Restful Spring Services
  • Java: Change a value in an overridden method of a different class to a value that was calculated in the class
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co