User Tools

Site Tools


cs257:proj3

Project 2

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.startWith("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.

cs257/proj3.txt · Last modified: 2017/02/15 17:53 by scarl