Home Ask Login Register

Developers Planet

Your answer is one click away!

daman February 2016

Simple Computing Machine

I'm working on a Von Neumann Machine, I'm writing a java program that works like a simple machine, that follows instructions. It reads a textfile and depending on the OpCode in the file, it either stores, adds, substract, multilply, divide and load numbers. Should I use a switch statement or alot of if else statements?

  • 01 07 // load 7 to Accumulator
  • 21 91 // store Accumulator M1
  • 05 13 // add 13 to 7 and keep 20 in the Acc.
  • 99 99 // print Acc. contents
  • 06 12 // subtract 12 from Acc.
  • 21 91 // store 8 to M1

    public class Machine{
    public static void main(String[] args) throws FileNotFoundException
    

    {

      File file = new File("U:/op.txt");
      Scanner readfile = new Scanner(file);
    
        while(readfile.hasNextInt()){
          String read = readfile.nextLine();
    
          System.out.println(read);
        }
    
    
    }
    

Answers


S.Klumpers February 2016

Use this:

import java.io.*;
import java.util.Scanner;

public class Machine{
    public static void main(String[] args) throws FileNotFoundException
    {
        File file = new File("U:/op.txt");
        Scanner readfile = new Scanner(file);

        int acc = 0;
        int M1 = 0;

        while(readfile.hasNextInt())
        {
            String read = readfile.nextLine();

            switch(read.substring(0, 2))
            {
                case "01":
                    acc = M1 + Integer.parseInt(read.substring(3, 5));
                    System.out.println(acc);
                break;
            }
        }
    }
}

The read.substring(0, 2) gets the first two characters. The read.substring(3, 5) gets the other two and Integer.parseInt(intString) gets the integer value of these two characters.

This can be reused for all your examples by adding in the other cases in the switch.

Post Status

Asked in February 2016
Viewed 3,928 times
Voted 6
Answered 1 times

Search




Leave an answer


Quote of the day: live life