Está en la página 1de 7

MC Juan Fraustro de la O Lenguajes y Autómatas

Proyecto Léxico, Agosto 2023

Palabras Reservadas.

public int nextLine if switch


private double nextInt else case
class String nextDouble do default
void new println while
Operadores Aritméticos:
+ - * / % =

Operadores Relacionales:
< <= > >= == !=

Operadores Lógicos:
! && ||

Caracteres : (que generan token)


; [ ] , : ( ) { }

Caracteres que NO generan token:


“ . BCO TAB EOLN EOF

Identificadores: Inician con letra, y pueden continuar con letras o dígitos.

Constantes Enteras. Son como regularmente se conocen, pueden o no llevar signo, una
constante entera se ubica en el intervalo de -32768 a 32767, si se encuentra fuera de ese rango
automáticamente se convierte en número real.

Constantes Reales: Pueden o no llevar signo. Pueden iniciar con punto decimal pero no pueden
terminar con punto decimal. No permiten notación científica.

Constante string: Van limitadas por “ al inicio y al final. Un string debe terminar en la misma
línea, no hay manera de continuarlo en otra línea.

Comentarios: El lenguaje permite comentarios inician con // y debe terminar en la misma línea.

jueves, 14 de diciembre de 2023 Página 1 de 7


MC Juan Fraustro de la O Lenguajes y Autómatas

public -1 int -5 nextLine -9 if -13 switch -17


private -2 double -6 nextInt -10 else -14 case -18
class -3 String -7 nextDouble -11 do -15 default -19
void -4 new -8 println -12 while -16

Constante -20 Constante -21 Identificadores -22 Constant -23 + -24


String entera e real
- -25 * -26 / -27 % -28 = -29
< -30 <= -31 > -32 >= -33 == -34
¡= -35 ¡ -36 && -37 || -38 ; -39
[ -40 ] -41 , -42 : -43 ( -44
) -45 { -46 } -47

Ejemplo de código:
int n=5;
23.56

Lexema Token Posición en Tabla Numero de línea


int -5 -1 1
n -22 -2 1
= -29 -1 1
5 -21 -1 1
; -39 -1 1
23.56 -23 -1 2

Donde la posición en tabla es -1 en cualquier caso excepto cuando es un identificador


public -1
int -5
nextLine -9
if -13
switch -17
private -2
double -6
nextInt -10
else -14
case -18
class -3
String -7
nextDouble -11
do -15
default -19
void -4
new -8
println -12
while -16
Constante String -20
Constante entera -21
Identificadores -22

jueves, 14 de diciembre de 2023 Página 2 de 7


MC Juan Fraustro de la O Lenguajes y Autómatas

Constante real -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

jueves, 14 de diciembre de 2023 Página 3 de 7


MC Juan Fraustro de la O Lenguajes y Autómatas

CÓDIGO

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication6;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AnalizadorLexico {


private static final String[] PALABRAS_RESERVADAS = {
"public", "int", "nextLine", "if", "switch",
"private", "double", "nextInt", "else", "case",
"class", "String", "nextDouble", "do", "default",
"void", "new", "println", "while"
};

private static final String OPERADORES_ARITMETICOS = "\\+|\\-|\\*|/|%|=";


private static final String OPERADORES_RELACIONALES = "<|<=|>|>=|==|!=";
private static final String OPERADORES_LOGICOS = "!|&&|\\|\\|";
private static final String CARACTERES_TOKEN = ";|\\[|\\]|,|:|\\(|\\)|\\{|\\}";

public static void main(String[] args) {


ArrayList<String> tokens = new ArrayList<>();
int numeroLinea = 1;

try {
BufferedReader reader = new BufferedReader(new FileReader("codigo.txt"));
String linea;
while ((linea = reader.readLine()) != null) {

if (linea.trim().startsWith("//")) {
continue;
}

String[] palabras = linea.split("\\s+");


for (String palabra : palabras) {
if (palabra.isEmpty()) {
continue; // Ignorar espacios en blanco
}

jueves, 14 de diciembre de 2023 Página 4 de 7


MC Juan Fraustro de la O Lenguajes y Autómatas

if (esPalabraReservada(palabra)) {
tokens.add(palabra + "\t" + getToken(palabra) + "\t-1\t" + numeroLinea);
} else if (palabra.matches("[a-zA-Z][a-zA-Z0-9]*")) {
tokens.add(palabra + "\t-22\t-2\t" + numeroLinea);
} else if (palabra.matches("-?\\d+")) {
if (esEnteroValido(palabra)) {
tokens.add(palabra + "\t-21\t-1\t" + numeroLinea);
} else {
tokens.add(palabra + "\t-23\t-1\t" + numeroLinea);
}
} else if (palabra.matches("-?\\d+(\\.\\d+)?")) {
tokens.add(palabra + "\t-23\t-1\t" + numeroLinea);
} else if (palabra.matches("\"[^\"]*\"")) {
tokens.add(palabra + "\t-20\t-1\t" + numeroLinea);
} else if (palabra.matches(OPERADORES_ARITMETICOS)) {
tokens.add(palabra + "\t" + "oparit" + "\t-1\t" + numeroLinea);
} else if (palabra.matches(OPERADORES_RELACIONALES)) {
tokens.add(palabra + "\t" + palabra + "\t-1\t" + numeroLinea);
} else if (palabra.matches(OPERADORES_LOGICOS)) {
tokens.add(palabra + "\t" + palabra + "\t-1\t" + numeroLinea);
} else if (palabra.matches(CARACTERES_TOKEN)) {
tokens.add(palabra + "\t" + palabra + "\t-1\t" + numeroLinea);
} else if (palabra.matches("[\\d]+\\)")) {
// Separar los caracteres '9' y ')' para analizarlos por separado
tokens.add(palabra.substring(0, palabra.length() - 1) + "\t-21\t-1\t" +
numeroLinea);
tokens.add(")" + "\t" + ")" + "\t-1\t" + numeroLinea);
} else {
// Tratar de dividir los caracteres de operadores
Matcher matcher = Pattern.compile("([&|])").matcher(palabra);
while (matcher.find()) {
tokens.add(matcher.group() + "\t" + matcher.group() + "\t-1\t" + numeroLinea);
}
tokens.add(palabra + "\tERROR\t-1\t" + numeroLinea);
}
}
numeroLinea++;
}
reader.close();
} catch (IOException e) {
System.out.println("Error al leer el archivo.");
e.printStackTrace();
}

System.out.println("Lexema\tToken\tPosición en Tabla\tNúmero de Línea");


for (String token : tokens) {
System.out.println(token);

jueves, 14 de diciembre de 2023 Página 5 de 7


MC Juan Fraustro de la O Lenguajes y Autómatas

}
}

private static boolean esPalabraReservada(String cadena) {


for (String palabra : PALABRAS_RESERVADAS) {
if (palabra.equals(cadena)) {
return true;
}
}
return false;
}

private static String getToken(String palabra) {


switch (palabra) {
case "public":
return "-1";
case "int":
return "-5";
case "nextLine":
return "-6";
case "if":
return "-7";
case "switch":
return "-17";
case "private":
return "-2";
case "double":
return "-6";
case "nextInt":
return "-10";
case "else":
return "-14";
case "case":
return "-18";
case "class":
return "-3";
case "String":
return "-7";
case "nextDouble":
return "-11";
case "do":
return "-15";
case "default":
return "-19";
case "void":
return "-4";
case "new":

jueves, 14 de diciembre de 2023 Página 6 de 7


MC Juan Fraustro de la O Lenguajes y Autómatas

return "-8";
case "println":
return "-12";
case "while":
return "-16";
default:
return "ERROR";
}
}

private static boolean esEnteroValido(String cadena) {


try {
int valor = Integer.parseInt(cadena);
return valor >= -32768 && valor <= 32767;
} catch (NumberFormatException e) {
return false;
}
}
}

jueves, 14 de diciembre de 2023 Página 7 de 7

También podría gustarte