简单计算机器
Simple Computing Machine
我在冯·诺依曼机器上工作,我正在编写一个 java 程序,它像一台简单的机器一样工作,遵循指令。它读取一个文本文件,并根据文件中的 OpCode,存储、添加、减去、乘法、除法和加载数字。我应该使用 switch 语句还是大量的 if else 语句?
- 01 07 // 将 7 加载到累加器
- 21 91 // 存储累加器 M1
- 05 13 // 将 13 加到 7 并在 Acc.
中保留 20
- 99 99 // 打印 Acc。内容
- 06 12 // 从 Acc.
中减去 12
21 91 // 将 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);
}
}
使用这个:
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;
}
}
}
}
read.substring(0, 2)
获取前两个字符。
read.substring(3, 5)
获取另外两个,Integer.parseInt(intString)
获取这两个字符的整数值。
通过在开关中添加其他案例,可以将其重复用于所有示例。
我在冯·诺依曼机器上工作,我正在编写一个 java 程序,它像一台简单的机器一样工作,遵循指令。它读取一个文本文件,并根据文件中的 OpCode,存储、添加、减去、乘法、除法和加载数字。我应该使用 switch 语句还是大量的 if else 语句?
- 01 07 // 将 7 加载到累加器
- 21 91 // 存储累加器 M1
- 05 13 // 将 13 加到 7 并在 Acc. 中保留 20
- 99 99 // 打印 Acc。内容
- 06 12 // 从 Acc. 中减去 12
21 91 // 将 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); } }
使用这个:
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;
}
}
}
}
read.substring(0, 2)
获取前两个字符。
read.substring(3, 5)
获取另外两个,Integer.parseInt(intString)
获取这两个字符的整数值。
通过在开关中添加其他案例,可以将其重复用于所有示例。