java - Simple Computing Machine -
this question has answer here:
- java: if vs. switch 11 answers
i'm working on von neumann machine, i'm writing java program works simple machine, follows instructions. reads textfile , depending on opcode in file, either stores, adds, substract, multilply, divide , load numbers. should use switch statement or alot of if else statements?
- 01 07 // load 7 accumulator
- 21 91 // store accumulator m1
- 05 13 // add 13 7 , keep 20 in acc.
- 99 99 // print acc. contents
- 06 12 // subtract 12 acc.
21 91 // store 8 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 first 2 characters. read.substring(3, 5)
gets other 2 , integer.parseint(intstring)
gets integer value of these 2 characters.
this can reused examples adding in other cases in switch.
Comments
Post a Comment