User Tools

Site Tools


Project 1

Reading Files

The link Using Scanner to Read Files adds a few details to the examples we've done using Scanner and File together.

Examples of using String Class Methods

For this example, we'll assume you have an instruction stored as a String object called instr.

Here's what you know: certain instructions (like pop, add, dump, etc.) take no argument value. So, you can use the equals methods for String to check if your instruction is one of those. But if instr holds something like “push -12” you can't use equals since you don't know in advance what the argument value will be.

Instead, you can use those other String methods we talked about, for example:

  if (instr.startsWith("push")) {           // if true, we have a push instruction
     String[] val = instr.split(" ");      // split breaks the string into substrings delimited by the space
                                           // and puts each substring in the array val
     int value = Integer.parseInt(val[1]); // parseInt converts a string of digits into an integer
     // **now complete the push operation**

The split method works by dividing the string up into pieces not including the space. So for the instruction push -12 the result of instr.split(“ ”); is a two-element String array and:

  val[0] contains "push"
  val[1] contains "-12"

In the above example I assume your stack holds objects of type Integer. If you're using Byte instead, modify accordingly.


It appears newer versions of Java tightened up rules on casting. To fix some issues I've seen:

In dump, trying to output members of the elements array can cause casting errors at runtime. A simple workaround is

Object[] elementsCopy = elements;
for (int i = 0; i <= topIndex; i++) {
   System.out.println((Short) elementsCopy[i]);

When using inheritance, prefer calling superclass methods to accessing protected instance variables. For example:

   short x, y, z;
   x =;
   y =;
   z = (short) (x + y); // cast because type of the result is int
cs257/proj3.txt · Last modified: 2021/03/22 13:41 by scarl