public static ArrayList parse(Scanner tokens) { ArrayList instructions = new ArrayList(); Instruction nextInstruction; String thisToken; int tokenIndex; ArrayList jzTokens = new ArrayList(); int jzIndex; while(tokens.hasNext()) { thisToken = tokens.next(); if (!validInstruction(thisToken)) { // invalid token, return null return null; } else { // add the instruction to the ArrayList nextInstruction = new Instruction(thisToken); instructions.add(nextInstruction); } tokenIndex = instructions.size() - 1; if (thisToken.equals("jz")) { // record the index of the JZ jzTokens.add(tokenIndex); } else if (thisToken.equals("jump")) { if (jzTokens.size() == 0) { // We received a JUMP token, but we do not have any JZ // tokens to associate it with. Return null. return null; } else { // Set the matching jump indexes for this jump token jzIndex = jzTokens.get(jzTokens.size() - 1); instructions.get(tokenIndex).setMatchingJump(jzIndex); instructions.get(jzIndex).setMatchingJump(tokenIndex); jzTokens.remove(jzTokens.size() - 1); } } } if (jzTokens.size() > 0) { // too many JZ instructions return null; } return instructions; }