开发者

JAVA: subclasses, self-learning-test, coursework, homework

开发者 https://www.devze.com 2022-12-18 06:18 出处:网络
HI ALL! As a part of my self-learning of Java I\'m trying to complete one of the Java begginer assignments available here (very old stuff - 2001)

HI ALL!

As a part of my self-learning of Java I'm trying to complete one of the Java begginer assignments available here (very old stuff - 2001)

The problem is that I don't know how to approach this challenge :( I will appreciate any suggestions as solution is not available any more, only link to zipped archives works fine.

Regards, Mary

PS. Assignment:

**"**Assignment 3: Assignment for Topic 3, SubClasses

(this is a revision of a project created by Prof. Cindy Norris of CS, Appalachian State University)

The goal of this assignment is to give you practice with subclasses in a setting where they are particularly useful. You will write an interpreter for a minimal machine language - MML. The general form of a machine language instruction is

label instruction register-list

label is the label for the line. Other instructions might "jump" to that label.

instruction is the actual instruction. In MML, there are instructions for adding, multiplying and so on, for storing and retrieving integers, and for conditionally branching to other labels (like an if statement).

register-list is the list of registers that the instruction manipulates. Registers are simple, integer, storage areas in computer memory, much like variables. In MML, there are 32 registers, numbered 0, 1, ..., 31.

MML has the following instructions:

L1 add r s1 s2 - Add the contents of registers s1 and s2 and store the result in register r.

L1 sub r s1 s2 - Subtract the contents of register s2 from the contents of s1 and store the result in register r.

L1 mul r s1 s2 - Multiply the contents of registers s1 and s2 and store the result in register r.

L1 div r s1 s2 - Divide (Java integer division) the contents of register s1 by the contents of register s2 and store the result in register r.

L1 out s1 - Print the contents of register s1 on the Java console (using println).

L1 lin r x - Store integer x in register r.

L1 bnz s1 L2 If the contents of register s1 is not zero, then make the statement labeled L2 the next one to execute.

We kept the number of different instructions small so that you would have less work to do. For example, there could have been other branch instructions, a negation instruction, an input instruction, and so on. But once you implement this little language, you will be easy for you to add more instructions.

L1 is any identifier --actually, any sequence of non-whitespace characters. Each statement of a program must be labeled with a different identifier. Each of s1, s2, and r is an integer in the range 0..31 and refers to one of the 32 registers in the machine that executes langu开发者_StackOverflow中文版age MML. Here is an example of an MML program to compute factorial 6. Note that adjacent fields of an instruction (label, opcode, and operands) are separated by whitespace.

f0  lin 20 6
f1  lin 21 1
f2  lin 22 1
f3  mul 21 21 20
f4  sub 20 20 22
f5  bnz 20 f3
f6  out 21

Instructions of a program are executed in order (starting with the first one), unless the order is changed by execution of a bnz instruction. Execution terminates when its last instruction has been executed (and doesn't change the order of execution).

Your interpreter will

  1. Obtain from the user the name of a file that contains the program,
  2. Read the program from the file and translate it into an internal form,
  3. Print the program,
  4. Execute the program, and
  5. Print the final value of the registers."

Machine.java

import java.util.*;

// The machine language interpreter
public class Machine {
    // The labels in the MML program, in the order in which
    // they appear (are defined) in the program
    private Labels labels= new Labels(); 

    // The MML program, consisting of prog.size() instructions, each
    // of class Instruction (or one of its subclasses)
    private Vector prog= new Vector();   

    // The registers of the MML machine
    private Registers registers;

    // The program counter; it contains the index (in prog) of
    // the next instruction to be executed.
    private int PC= 0;

    public static void main (String[] pars) {

        Machine m= new Machine();
        Translator.readAndTranslate(m.labels, m.prog);

        System.out.println("Here is the program; it has " +
      m.prog.size() + " instructions.");
        m.print();
        System.out.println();

        System.out.println("Beginning program execution.");
        m.execute();
 System.out.println("Ending program execution.");

        System.out.println("Values of registers at program termination:");
        System.out.println(m.registers + ".");
 System.exit(0);
    }

    // Print the program
    public void print() {
        for (int i= 0; i != prog.size(); i++) {
            System.out.println((Instruction) prog.elementAt(i));
        }
    }

    // Execute the program in prog, beginning at instruction 0.
    // Precondition: the program and its labels have been store properly.
    public void execute() {
 PC= 0;
 registers= new Registers();
 while (PC < prog.size()) {
     Instruction ins= (Instruction)prog.elementAt(PC);
     PC= PC+1;
     ins.execute(this);
 }
    }

    // = the registers of this machine
    public Registers getRegisters() {
 return registers;
    }

    // = the labels of this machine
    public Labels getLabels() {
 return labels;
    }

    // Set the program counter to pc
    public void setPC(int pc) {
 PC= pc;
    }
}

Translator.java

import  java.io.*;
import  java.util.*;
import  javax.swing.*;

// The translator of a small program. All the fields and methods are static.
public class Translator {
    private static BufferedReader br; // Reader attached to the file chosen by the user

    // word + line is the part of the current line that's not yet processed
    // word has no whitespace
    // If word and line are not empty, line begins with whitespace
    private static String line="";    
    private static String word=""; 

    private static Labels labels; // The labels of the program being translated 
    private static Vector program;   // The program to be created  

    // Obtain a file name from the user and translate the 
    // small program in that file into lab (the labels) and
    // prog (the program)
    // return "no errors were detected"
    public static boolean readAndTranslate(Labels lab, Vector prog) {
        try {
            getReader();
        } catch(IOException ioE) {
            System.out.println("Sai: IO error to start " );
            return false;
        }
        labels= lab;
        labels.reset();
        program= prog;
        program.removeAllElements();

        try { line = br.readLine();
        }
        catch (IOException ioE) {
            return false;
        }

        // Each iteration processes line and reads the next line into line
        while (line != null) {
            // Store the label in label
     String label= scan(); 

            if (label.length() > 0) {

                Instruction ins= getInstruction(label);
                if ( ins != null ) {
                    labels.addLabel(label); 
                    program.addElement(ins);  
                }
            }

            try { line = br.readLine();
            }
            catch (IOException ioE) {
                return false;
            }

        }
        return true;
    }

    // line should consist of an MML instruction, with its label already
    // removed. Translate line into an instruction with label label
    // and return the instruction
    public static Instruction getInstruction(String label) {
        int s1;   // Possible operands of the instruction
        int s2;
        int r;
        int x;
        String L2;

        String ins= scan();
        if (line.equals("")) return null;

        if (ins.equals("add")) {
            r= scanInt();
            s1= scanInt();
            s2= scanInt();
            return new AddInstruction(label, r, s1, s2);
        }

        // You will have to write code here for the other instructions.

        return null;
     }


     // Display a JFileChooser and set br to a reader for the file chosen
     private static void getReader() throws IOException {
       JFileChooser chooser = new JFileChooser("C:\\Windows\\Desktop\\compiler\\test0.txt");
       chooser.setDialogTitle("Choose the File that contains the MML program to be executed");
       chooser.showOpenDialog(null);
       br =  new BufferedReader(new FileReader(chooser.getSelectedFile()));
     }

    // Return the first word of line and remove it from line.
    // If there is no word, return ""
    public static String scan() {
        line= line.trim();
        if (line.length() == 0) 
            {   return "";   }
        int i= 0;
        while (i < line.length() &&
               line.charAt(i) != ' ' &&
               line.charAt(i) != '\t') {
            i= i+1;
        }
        word= line.substring(0,i);
        line= line.substring(i);
        return word;
    }

    // Return the first word of line as an integer. If there is
    // any error, return the maximum int
    public static int scanInt() {
        String word= scan();
        if (word.length() == 0)
            { return Integer.MAX_VALUE; }

        try {
            return Integer.parseInt(word);
        } catch (NumberFormatException e) {
            return Integer.MAX_VALUE;
        }
    }
}

Labels.java

import java.util.*;

// An instance contains a list of Strings, called "labels",
// in the order in which they were added to the list. 
public class Labels {
    private Vector labels= new Vector();

    // Constructor: an empty list of labels
    public Labels() {
    }

    // Add label lab to this list and return its number in the list
    // (the first one added is number 0)
    // Precondition: the list has at most 49 entries
    public int addLabel(String lab) {
        labels.addElement(lab);
        return labels.size()-1;
    }

    // = the number of label lab in the list
    //   (= -1 if lab is not in the list)
    public int indexOf(String lab) {

        // invariant: lab is not in labels[0..i-1]
        for (int i= 0; i != labels.size(); i++) {
            if (lab.equals((String)(labels.elementAt(i)))) {
                return i;
            }
        }   
        return -1;
    }

    // representation of this instance, "(label 0, label 1, ..., label (n-1))"
    public String toString() {
        String r= "(";
        // invariant: r contains the representation for labels[0..i-1]
        // (with the opening "(" but no closing ")")
        for (int i= 0; i != labels.size(); i++) {
            if (i == 0) {
                r= r + (String)(labels.elementAt(i));
            } else {
                r= r + ", " + (String)(labels.elementAt(i));
            }
        }
        r= r + ")";
        return r;
    }

    // Set the number of elements in the list to 0
    public void reset() {
        labels.removeAllElements();
    }
}

Registers.java

// An instance contains 31 registers and methods to access
// and change them
public class Registers {
    private int registers[]= new int[31];

    // Constructor: an instance whose registers are set to 0
    public Registers() {
        for (int i= 0; i != registers.length; i++) {
            registers[i]= 0;
        }
    }

    // = the value in register i.
    // Precondition: 0 <= i < 32
    public int getRegister(int i) {
        return registers[i];
    }

    // Set register i to v.
    // Precondition: 0 <= i < 32
    public void setRegister(int i, int v) {
        registers[i]= v;
    }

    // =  a representation of the registers,
    //    "(reg 0, reg 1, ..., reg 31)"
    public String toString() {
        String r= "(" + registers[0];
        // invariant: r contains the representation for registers[0..i-1]
        // (with the opening "(" but no closing ")")
        for (int i= 1; i != registers.length; i++) {
            r= r + ", " + registers[i];
        }
        r= r + ")";
        return r;
    }
}

Instruction.java

// This class is the superclass of the classes for machine instructions
public abstract class Instruction {

    // Constructor: an instruction with label l and opcode op
    // (op must be an operation of the language)
    public Instruction(String l, String op) {
    }

    // = the representation "label: opcode" of this Instruction
    public String toString() {
        return "";
    }

    // Execute this instruction on machine m. 
    public abstract void execute(Machine m);
}


The way the assignment is leaning, it appears you're supposed to subclass Instruction - forex:

public class AddInstruction implements Instruction{

    public AddInstruction(String l, int r, int s1, int s2) {
        // Store the stuff passed in
    }

    public void execute(Machine m) {
        Registers reg = m.getRegisters();
        reg.setRegister(r, reg.getRegister(s1) + reg.getRegister(s2));
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号