Advertisement
claukiller

Untitled

Jan 15th, 2017
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. public class Main {
  5.  
  6. private static List<String[]> instrucciones = new ArrayList<String[]>();
  7. private static int ip = 0;
  8.  
  9. private static int[] memoria = new int[1024];
  10.  
  11. private static int[] pila = new int[32];
  12. private static int sp = 0;
  13.  
  14. public static void main(String[] args) throws Exception {
  15. BufferedReader fichero = new BufferedReader(new FileReader("factorial.txt"));
  16.  
  17. String linea;
  18. while ((linea = fichero.readLine()) != null)
  19. cargaInstrucción(linea);
  20. fichero.close();
  21.  
  22. ejecutaPrograma();
  23. }
  24.  
  25. private static void ejecutaPrograma() {
  26. while (ip < instrucciones.size()) {
  27. String[] instruccion = instrucciones.get(ip);
  28.  
  29. if (instruccion[0].equals("push")) {
  30. push(Integer.parseInt(instruccion[1]));
  31. ip++;
  32. } else if (instruccion[0].equals("add")) {
  33. push(pop() + pop());
  34. ip++;
  35. } else if (instruccion[0].equals("sub")) {
  36. int b = pop();
  37. int a = pop();
  38. push(a - b);
  39. ip++;
  40. } else if (instruccion[0].equals("mul")) {
  41. push(pop() * pop());
  42. ip++;
  43. } else if (instruccion[0].equals("jmp")) {
  44. ip = Integer.parseInt(instruccion[1]);
  45. } else if (instruccion[0].equals("jmpg")) {
  46. int b = pop();
  47. int a = pop();
  48. if (a > b)
  49. ip = Integer.parseInt(instruccion[1]);
  50. else
  51. ip++;
  52. } else if (instruccion[0].equals("load")) {
  53. int direccion = pop();
  54. push(memoria[direccion]);
  55. ip++;
  56. } else if (instruccion[0].equals("store")) {
  57. int valor = pop();
  58. int direccion = pop();
  59. memoria[direccion] = valor;
  60. ip++;
  61. } else if (instruccion[0].equals("input")) {
  62. System.out.println("Escriba un entero:");
  63. push(leerValor());
  64. ip++;
  65. } else if (instruccion[0].equals("output")) {
  66. System.out.println(pop());
  67. ip++;
  68. }
  69. }
  70. }
  71.  
  72. private static void cargaInstrucción(String linea) {
  73. if (linea.trim().length() == 0)
  74. return;
  75.  
  76. String[] palabras = linea.split(" ");
  77. instrucciones.add(palabras);
  78. }
  79.  
  80. private static void push(int valor) {
  81. pila[sp] = valor;
  82. sp++;
  83. }
  84.  
  85. private static int pop() {
  86. sp--;
  87. return pila[sp];
  88. }
  89.  
  90. private static int leerValor() {
  91. return new Scanner(System.in).nextInt();
  92. }
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement