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?
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);
}
}
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.