Java - Automata que lee tokens de un documento txt

 
Vista:

Automata que lee tokens de un documento txt

Publicado por AdrianJ (1 intervención) el 03/05/2021 05:51:29
Este codigo te lee los caracteres de los siguientes documentos txt, lo que se tiene que hacer es que tambien sea capaz de leer caracteres de delimitadores:
( ) [ ] { }
, : . ; @ = ->
+= -= *= /= //= %= @=
&= |= ^= >>= <<= **=

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class Principal{
 
   public static void main(String[] args){
	   boolean aceptado;
	   String token, tipo, sintaxis;
	   int idlexema;
       TAutomata lexico = new TAutomata();
       TablaSimbolos ts = new TablaSimbolos();
       TAutSintactico sintactico = new TAutSintactico();
 
       // Análisis Léxico
       token = "1234";
       aceptado = lexico.EvaluaAutomata(token);
       if (aceptado){
           tipo = lexico.getTipo();
           idlexema = lexico.getIdLexema();
           System.out.printf("Token: %s\nTipo: %s\nLexema: %d\nAceptado: %b\n", token, tipo, idlexema, aceptado);
           ts.agregaFila(token, tipo, idlexema, 0, false, 0);
           System.out.println("\nContenido tabla de simbolos:");
           ts.muestaTS();
	   }
 
	   // Análisis Sintáctico
	   //sintaxis = "81363546CD3E69";
	   sintaxis = "823613613635763546CD3E35";
	   aceptado = sintactico.EvaluaAutomata(sintaxis);
	   System.out.println("Sintaxis correcta: " + aceptado);
 
   }
 
 
}  // Fin Principal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
public class FilaTS{
	private String token;
	private String tipo;
	private int idlexema;
	private int nolinea;
	private boolean refprevia;
	private int dirmem;
 
	FilaTS(){
		token = "";
		tipo = "";
		idlexema = 0;
		nolinea = 0;
		refprevia = false;
		dirmem = 0;
	}
 
	FilaTS(String token, String tipo, int idlexema, int nolinea, boolean refprevia, int dirmem){
		SetModificaTodo(token, tipo, idlexema, nolinea, refprevia, dirmem);
	}
 
 
	// Métodos Get
	public String GetToken(){
		return token;
	}
 
	public String GetTipo(){
		return tipo;
	}
 
	public int GetIdLexema(){
		return idlexema;
	}
 
	public int GetNoLinea(){
		return nolinea;
	}
 
	public boolean GetRefPrevia(){
		return refprevia;
	}
 
	public int GetDirMem(){
		return dirmem;
	}
 
	// Métodos Set
	public void SetModificaTodo(String token, String tipo, int idlexema, int nolinea, boolean refprevia, int dirmem){
		this.token = token;
		this.tipo = tipo;
		this.idlexema = idlexema;
		this.nolinea = nolinea;
		this.refprevia = refprevia;
		this.dirmem = dirmem;
	}
 
	public void SetToken(String token){
		this.token = token;
	}
 
	public void SetTipo(String tipo){
		this.tipo = tipo;
	}
 
	public void SetIdLexema(int idlexema){
		this.idlexema = idlexema;
	}
 
	public void SetNoLinea(int nolinea){
		this.nolinea = nolinea;
	}
 
	public void SetRefPrevia(boolean refprevia){
		this.refprevia = refprevia;
	}
 
	public void SetDirMem(int dirmem){
		this.dirmem = dirmem;
	}
 
	@Override
	public String toString(){
		String cadena = "";
 
		cadena = "Token: " + GetToken() + "\n" +
				 "Tipo: " + GetTipo() + "\n" +
				 "Identificador del lexema: " + Integer.toString(GetIdLexema()) + "\n" +
				 "Numero de linea: " + Integer.toString(GetNoLinea()) + "\n" +
				 "Existe referencia previa: " + Boolean.toString(GetRefPrevia()) + "\n" +
				 "Direccion de memoria interna del token: " + Integer.toString(GetDirMem()) + "\n";
		return cadena;
	}
 
}  // Fin FilaTS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.util.ArrayList;
import java.util.Iterator;
 
public class TablaSimbolos{
	private ArrayList<FilaTS> ts;
 
	TablaSimbolos(){
		ts = new ArrayList<>();
	}
 
	public void agregaFila(String token, String tipo, int idlexema, int nolinea, boolean refprevia, int dirmem){
		FilaTS fila = new FilaTS(token, tipo, idlexema, nolinea, refprevia, dirmem);
		ts.add(fila);
	}
 
	public void muestaTS(){
		Iterator<FilaTS> it = ts.iterator();
		FilaTS fila = new FilaTS();
		while (it.hasNext()){
			fila =it.next();
			System.out.println(fila.toString());
		}
	}
 
} // Fin clase TablaSimbolos
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import java.io.*;
 
public class TAutomata{
   private String sigma;
   private int edoinicial, edofinal, no_edos;
   private int delta[][];
   private String tipo;
   private int idlexema;
 
 
   TAutomata(){
	   sigma=LeerAlfabeto();
	   //System.out.println(sigma);
	   //System.out.println(sigma.length());
	   LeerDelta();
	   tipo = "";
	   idlexema = 0;
   }
 
   private String LeerAlfabeto(){
	  File archivo = null;
      FileReader fr = null;
      BufferedReader br = null;
      String linea = "";
 
      try {
         // Apertura del fichero y creacion de BufferedReader para poder
         // hacer una lectura comoda (disponer del metodo readLine()).
         archivo = new File ("alfabeto.txt");
         fr = new FileReader (archivo);
         br = new BufferedReader(fr);
 
         // Lectura del fichero
         linea = br.readLine();
         //System.out.println("Modo depuracion: " + linea);
         //System.out.println("Modo depuracion (tamanio cadena): " + linea.length());
      }
      catch(Exception e){
         e.printStackTrace();
      }
      finally{
         // En el finally cerramos el fichero, para asegurarnos
         // que se cierra tanto si todo va bien como si salta
         // una excepcion.
         try{
            if( null != fr ){
               fr.close();
            }
         }
         catch (Exception e2){
            e2.printStackTrace();
         }
      }
      return linea;
   }
 
 
   private void LeerDelta(){
	  File archivo = null;
      FileReader fr = null;
      BufferedReader br = null;
 
 
      try {
         // Apertura del fichero y creacion de BufferedReader para poder
         // hacer una lectura comoda (disponer del metodo readLine()).
         archivo = new File ("lexico2.txt");
         fr = new FileReader (archivo);
         br = new BufferedReader(fr);
         String linea = "";
         int nfilas, ncol;
 
         // Lectura del fichero
         linea = br.readLine();
         //System.out.println("Modo depuracion: " + linea + " (tamanio cadena): " + linea.length());
         nfilas = Integer.parseInt(linea);
         linea = br.readLine();
         //System.out.println("Modo depuracion: " + linea + " (tamanio cadena): " + linea.length());
         ncol = Integer.parseInt(linea);
         //System.out.println("Modo depuracion. No. filas: " + nfilas + " No. col: " + ncol);
         delta = new int[nfilas][ncol];
         edoinicial=0;
	     //edofinal=4;
	     no_edos=nfilas;
 
         for (int i=-1; i<nfilas; i++){
			 String[] splited = linea.split("\t");
			 for (int j=0; j<splited.length; j++){
				  if (i>=0)
				      delta[i][j] = Integer.parseInt(splited[j]);
				  //System.out.print(splited[j]+ " ");
			 }
			 linea = br.readLine();
			 //System.out.println();
	     }
 
	     /*
	     /// Quitar
	     System.out.println("Matriz delta");
	     for (int i=0; i<nfilas; i++){
			 for (int j=0; j<ncol; j++){
				  System.out.print(delta[i][j] + " ");
			 }
			 System.out.println();
	     }
	     /// Quitar
	     */
      }
      catch(Exception e){
         e.printStackTrace();
      }
      finally{
         // En el finally cerramos el fichero, para asegurarnos
         // que se cierra tanto si todo va bien como si salta
         // una excepcion.
         try{
            if( null != fr )
               fr.close();
         }
         catch (Exception e2){
            e2.printStackTrace();
         }
      }
   }
 
 
   private int BuscaCar(char letra){
	   int indice;
	   boolean encontrado = false;
 
	   indice = 0;
	   while (indice<sigma.length() && !encontrado){
		   if (letra == sigma.charAt(indice))
		      encontrado = true;
		   indice++;
	   }
	   if (encontrado)
	      return --indice;
	   else
	      return -1;
   }
 
   public boolean EvaluaAutomata(String cadena){
	   boolean aceptado = false;
	   boolean error = false;
	   int edoactual, edoanterior, ic, lc, j;
 
	   ic = 0;
	   lc = cadena.length();
	   edoactual = edoinicial;
	   while (ic<lc && !error){
		  edoanterior = edoactual;
		  j = BuscaCar(cadena.charAt(ic));
		  if (j!=-1)
		      edoactual = delta[edoanterior][j];
		  else
		      error = true;
		  ic++;
	   }
	   if (edoactual>0 && !error){
	       aceptado = true;
	       switch (edoactual){
			   case 7:
						tipo = "Palabra reservada int";
						idlexema = 1;
						//System.out.println(tipo);
						break;
			   case 10:
			            tipo = "Palabra reservada float";
			            idlexema = 2;
						//System.out.println(tipo);
						break;
			   case 4:
						tipo = "Numero entero";
						idlexema = 4;
						//System.out.println(tipo);
						break;
			   default:
						tipo = "Identificador";
						idlexema = 3;
						//System.out.println(tipo);
		   }
	   }
	   else{
	       aceptado = false;
	       System.out.printf("Error, token no v%clido\n", 160);
	   }
 
	   return aceptado;
   }
 
   public String getTipo(){
	   return tipo;
   }
 
   public int getIdLexema(){
	   return idlexema;
   }
 
 
} // Fin de la clase TAutomata
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import java.io.*;
 
public class TAutSintactico{
   private String sigma;
   private int edoinicial, edofinal, no_edos;
   private int delta[][];
   private String tipo;
   //private int idlexema;
 
 
   TAutSintactico(){
	   sigma=LeerAlfabeto();
	   System.out.println(sigma);
	   System.out.println(sigma.length());
	   LeerDelta();
	   tipo = "";
	   //idlexema = 0;
   }
 
   private String LeerAlfabeto(){
	  File archivo = null;
      FileReader fr = null;
      BufferedReader br = null;
      String linea = "";
 
      try {
         // Apertura del fichero y creacion de BufferedReader para poder
         // hacer una lectura comoda (disponer del metodo readLine()).
         archivo = new File ("alfaSintactico.txt");
         fr = new FileReader (archivo);
         br = new BufferedReader(fr);
 
         // Lectura del fichero
         linea = br.readLine();
         //System.out.println("Modo depuracion: " + linea);
         //System.out.println("Modo depuracion (tamanio cadena): " + linea.length());
      }
      catch(Exception e){
         e.printStackTrace();
      }
      finally{
         // En el finally cerramos el fichero, para asegurarnos
         // que se cierra tanto si todo va bien como si salta
         // una excepcion.
         try{
            if( null != fr ){
               fr.close();
            }
         }
         catch (Exception e2){
            e2.printStackTrace();
         }
      }
      return linea;
   }
 
 
   private void LeerDelta(){
	  File archivo = null;
      FileReader fr = null;
      BufferedReader br = null;
 
 
      try {
         // Apertura del fichero y creacion de BufferedReader para poder
         // hacer una lectura comoda (disponer del metodo readLine()).
         archivo = new File ("sintactico2.txt");
         fr = new FileReader (archivo);
         br = new BufferedReader(fr);
         String linea = "";
         int nfilas, ncol;
 
         // Lectura del fichero
         linea = br.readLine();
         System.out.println("Modo depuracion: " + linea + " (tamanio cadena): " + linea.length());
         nfilas = Integer.parseInt(linea);
         linea = br.readLine();
         System.out.println("Modo depuracion: " + linea + " (tamanio cadena): " + linea.length());
         ncol = Integer.parseInt(linea);
         System.out.println("Modo depuracion. No. filas: " + nfilas + " No. col: " + ncol);
         delta = new int[nfilas][ncol];
         edoinicial=0;
	     //edofinal=4;
	     no_edos=nfilas;
 
         for (int i=-1; i<nfilas; i++){
			 String[] splited = linea.split(" ");
			 for (int j=0; j<splited.length; j++){
				  if (i>=0)
				      delta[i][j] = Integer.parseInt(splited[j]);
				  //System.out.print(splited[j]+ " ");
			 }
			 linea = br.readLine();
			 //System.out.println();
	     }
 
 
	     /// Quitar
	     System.out.println("Matriz delta");
	     for (int i=0; i<nfilas; i++){
			 for (int j=0; j<ncol; j++){
				  System.out.print(delta[i][j] + " ");
			 }
			 System.out.println();
	     }
	     /// Quitar
 
      }
      catch(Exception e){
         e.printStackTrace();
      }
      finally{
         // En el finally cerramos el fichero, para asegurarnos
         // que se cierra tanto si todo va bien como si salta
         // una excepcion.
         try{
            if( null != fr )
               fr.close();
         }
         catch (Exception e2){
            e2.printStackTrace();
         }
      }
   }
 
 
   private int BuscaCar(char letra){
	   int indice;
	   boolean encontrado = false;
 
	   indice = 0;
	   while (indice<sigma.length() && !encontrado){
		   if (letra == sigma.charAt(indice))
		      encontrado = true;
		   indice++;
	   }
	   if (encontrado)
	      return --indice;
	   else
	      return -1;
   }
 
   public boolean EvaluaAutomata(String cadena){
	   boolean aceptado = false;
	   boolean error = false;
	   int edoactual, edoanterior, ic, lc, j;
 
	   ic = 0;
	   lc = cadena.length();
	   edoanterior = -1;
	   System.out.println("Modo depuracion -  cadena: " + cadena);
	   edoactual = edoinicial;
	   while (ic<lc && !error){
		  System.out.println("Modo depuracion - Estado actual: " + edoactual + " entrada: " + cadena.charAt(ic));
		  if (edoactual != -1){
		      edoanterior = edoactual;
		      j = BuscaCar(cadena.charAt(ic));
		      if (j!=-1)
		          edoactual = delta[edoanterior][j];
		      else
		          error = true;
		  }
		  else
		      error = true;
		  ic++;
	   }
	   System.out.println("Modo depuracion - Estado actual: " + edoactual + "\nEstado anterior: " + edoanterior);
	   if (edoactual==12 && !error){
	       aceptado = true;
	       switch (edoactual){
			   case 12:
						tipo = "Sentencia sintacticamente correcta";
						//idlexema = 1;
						System.out.println("Programa sintacticamente correcto");
						break;
			   /*default:
						tipo = "Identificador";
						idlexema = 3;
						//System.out.println(tipo);*/
		   }
	   }
	   else{
	       aceptado = false;
	       if (edoactual == -1){
	           switch (edoanterior){
				   case 1:
							System.out.println("Se esperaba } | print | identificador | int | float");
							break;
				   case 2:
							System.out.println("Se esperaba un identificador");
							break;
				   case 3:
							System.out.println("Se esperaba un identificador");
							break;
				   case 4:
							System.out.println("Se esperaba (");
							break;
				   case 5:
							System.out.println("Se esperaba ;");
							break;
				   case 6:
							System.out.println("Se esperaba un identificador | numero entero | numero flotante");
							break;
				   case 7:
							System.out.println("Se esperaba )");
							break;
			       case 8:
							System.out.println("Se esperaba ;");
							break;
				   case 9:
							System.out.println("Se esperaba un =");
							break;
				   case 10:
							System.out.println("Se esperaba un identificador | numero entero | numero flotante");
							break;
				   case 11:
							System.out.println("Se esperaba un + | * ");
							break;
		       }
	       }
	       else{
			   switch (edoactual){
				   case 1:
							System.out.println("Se esperaba } | print | identificador | int | float");
							break;
				   case 2:
							System.out.println("Se esperaba un identificador");
							break;
				   case 3:
							System.out.println("Se esperaba un identificador");
							break;
				   case 4:
							System.out.println("Se esperaba (");
							break;
				   case 5:
							System.out.println("Se esperaba ;");
							break;
				   case 6:
							System.out.println("Se esperaba un identificador | numero entero | numero flotante");
							break;
				   case 7:
							System.out.println("Se esperaba )");
							break;
			       case 8:
							System.out.println("Se esperaba ;");
							break;
				   case 9:
							System.out.println("Se esperaba un =");
							break;
				   case 10:
							System.out.println("Se esperaba un identificador | numero entero | numero flotante");
							break;
				   case 11:
							System.out.println("Se esperaba un + | * ");
							break;
			   }
		   }
	       //System.out.printf("Error, token no v%clido\n", 160);
	   }
	   return aceptado;
   }
   public String getTipo(){
	   return tipo;
   }
   /*
   public int getIdLexema(){
	   return idlexema;
   } */
 
 
} // Fin de la clase TAutomata
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder