Reporte de Identificador Codigo

45
INSTITUTO TECNOLOGICO DE CHILPANCINGO. LENGUAJES Y AUTOMATAS I. DOCUMENTACION DEL CODIGO. NOMBRE DEL ALUMNO: Morales García Julio Cesar. 27 de Febrero del 2013.

Transcript of Reporte de Identificador Codigo

Page 1: Reporte de Identificador Codigo

INSTITUTO TECNOLOGICO DE CHILPANCINGO.

LENGUAJES Y AUTOMATAS I.

DOCUMENTACION DEL CODIGO.

NOMBRE DEL ALUMNO:

Morales García Julio Cesar.

27 de Febrero del 2013.

Page 2: Reporte de Identificador Codigo

MARCO TEÓRICO.

Diagrama de tansición: es una colección finita de círculos los cuales se pueden rotular con fines de referencia conectados por flechas que reciben el nombre de arcos, cada uno de estos arcos se etiqueta con simbolos que puede representarse en la cadena de entrada que se analiza. Uno de los círculos se designa con un apuntador y representa una posición inicial, por lo menos un circulo se representa con circulo doble que indica que se ha reconocido una cadena valida.

Los circulos de un diagrama de transiciones representan posiciones o estados, donde nos podemos encontrar al ealuar una cadena de simbolos.

Ejemplo:

Diagrama de transicion para evaluar un identificador.

Page 3: Reporte de Identificador Codigo

Una vez que se tiene el diagrama de transiciones está bien definido para solo acepte cadenas validas se puede implementar en un programa siguiendo el algoritmo siguiente.

El algoritmo consiste en una condición case que se encarga de asignar los diferentes valores según el estado donde se encuentre.

A continuación se llevarán a cabo dos implementaciones en el lenguaje de programación Java, la primera es una versión estructurada y la segunda es bajo el enfoque orientado a objetos.

Page 4: Reporte de Identificador Codigo

Definición del problema:

Hacer un programa en JAVA que determine si un texto introducido desde el teclado es una notación científica o si se trata de texto simple.

Librerías necesarias para la creación del programa.

Clase Scanner: nos permite manejar la estrada a través del teclado en modo consola.

Clase Matcher: busca una expresión regular en el texto que se le indica.

Clase Pattern: nos permite definir una expresión regular.

Listado de variables necesarias.

La variable i: índice utilizado en las instrucciones for del programa, longitud: indica el número de caracteres de la cadena, puntos: indica el número de puntos que tiene la cadena, cantidadE: indica el número de letras (E o e) en la cadena, esNotacion: indica si la cadena es notación científica, e: indica si la cadena contiene letra (e o E).

Page 5: Reporte de Identificador Codigo

Las instancias de la clase Pattern indican la expresión regular que se buscará en la cadena, las instancias de la clase Matcher buscan coincidencias de las expresiones regulares en los caracteres de la cadena indicada.

Solicitar la entrada de una expresión numérica en notación científica.

Se pide al usuario ingresar una cadena de caracteres que presuntamente será una notación científica y se obtiene la cantidad de caracteres en la cadena.

En este punto comienzan las búsquedas de los patrones preestablecidos en los objetos Patter.

En el objeto obje se almacena el último carácter de la cadena, en la siguiente línea compara el patrón definido con el último carácter de la cadena, el objeto objet almacena el primer carácter de la cadena y la siguiente línea lo compara con el patrón.

En caso de que haya alguna coincidencia entre la cadena y el patrón el método find() de la clase Matcher retornará true, de ser de ser así se mostrará el mensaje y finalizará el programa.

Contar el número de puntos en la cadena.

Page 6: Reporte de Identificador Codigo

Este segmento cuenta el número de puntos que contiene la cadena, posteriormente evalúa si el número de puntos es mayor o igual a dos, de ser así asigna false a la variable esNotacion.

Contar las letras (e o E) en la cadena.

Este segmento cuenta el número de veces que encuentra la letra (e o E) en la cadena, encuentra una e, asigna a la variable e true , posteriormente evalúa si el número de puntos es igual a dos, de ser así asigna false a la variable esNotacion.

Buscar letras en la cadena.

Este segmento se encarga de buscar letras en la cadena, si encuentra letras se asigna false a la variable esNotacion, de lo contrario se realizan otras evaluaciones, si el número de puntos es 1 y si el número de letras e, es 1 se asigna true a la variable esNotacion, posteriormente se evalúa el resultado final de la variable esNotacion , si es verdadero se muestra el mensaje de que es notación de lo contrario el mensaje de que la cadena no es notación científica.

Page 7: Reporte de Identificador Codigo

Clase Automata.java

Atributos:

private int estado: contiene el estado actual del autómata.

private int estadoInicial: contiene el estado inicial.

private int estadoAnterior: almacena el estado anterior al estado actual.

int estadoFinal[]: contiene un arregle con los estados que se consideran como finales.

Constructor:

Public Automata(int estadoInicialNuevo, int estadosFinalNuevo[])

Recibe como parámetros un entero que es el estado final del autómata y un arreglo de enteros que contiene los valores para el estado que son considerados como finales.

Métodos:

public void setEstado(int estadoNuevo)

Este método recibe como parámetros un entero que representa el nueva estado y lo establece a la variable estado.

public int getEstado() Este método obtiene el valor de las variables estado.

public void setEstadoInicial(int estadoI)Este método establece el estado inicial. public int getEstadoInicial()Este método retorna el valor de la variable estadoInicial public void setEstadoAnterior(int estadoA)

Page 8: Reporte de Identificador Codigo

Establece el valor de la variable estadoAnterior public int getEstadoAnterior()Retorna el valor de la variables estadoAnterior. public boolean esFinal() Verifica si el ultimo estado obtenido es un estado final del autómata.

public int tipoSimbolo( char simbolo) Verifica que tipo de símbolo se esta analizando.Retorna 1: si es letra 0: si es numero -1: si es ninguno de los anteriores.

public int transicion(char simbolo)Se encarga de realizar la transición de un estado a otro en el autómata y de retornar el estado.

Clase ManejoCadena.java

Constructor:public ManejoCadena()Por defecto.

Métodos: public boolean esLetra(char simbolo)Recibe de parámetros un char y retorna verdadero si es una letra del abecedario.

public boolean esNumero(char simbolo)Recibe de parámetros un char y retorna verdadero si es un número.

Clase Manejoerrores.javaConstructor: por defecto.Métodos: String obtenerTexto(int i){

Page 9: Reporte de Identificador Codigo

Recibe como parámetro un entero que es el código de error generado al realizar una transición incorrecta y retorna el texto que indica el error al usuario.

Clase ManejoArchivos.java

Constructor: public ManejoArchivos() El constructor se encarga de escribir un archivo de texto con los posibles errores que se pueden generar al realizar la transición de estados en el autómata.Los errores están identificados con los códigos de error: -1 y -2 respectivamente. public String obtenerTexto(int i) recibe como parámetro un entero que el código de error generado por una transición que no puede llevarse a cabo y retorna el texto correspondiente que indica al usuario el tipo de error ocurrido en la transición.

Clase Informacion.java.

Presenta una interfaz gráfica donde se aprecian los datos del desarrollador del software y de su propósito.

Page 10: Reporte de Identificador Codigo

Clase InterfazIdentificador.java

Aquí se ingresará la cadena y se determinará si es un identificador válido o no, de no serlo se indicará el error.

Page 11: Reporte de Identificador Codigo
Page 12: Reporte de Identificador Codigo

/* * To change this template, choose Tools | Templates * and open the template in the editor. */package proyidentificador;

/** * * @author JULIOC */public class Automata { private int estado; private int estadoInicial; private int estadoAnterior; int estadoFinal[]; public Automata(int estadoInicialNuevo,int estadosFinalNuevo[]){ setEstadoInicial(estadoInicialNuevo); setEstado(estadoInicialNuevo); estadoFinal=estadosFinalNuevo; } public void setEstado(int estadoNuevo){ estado=estadoNuevo; } public int getEstado(){ return estado; } public void setEstadoInicial(int estadoI){ estadoInicial=estadoI; } public int getEstadoInicial(){ return estadoInicial; } public void setEstadoAnterior(int estadoA){ estadoAnterior=estadoA; } public int getEstadoAnterior(){

Page 13: Reporte de Identificador Codigo

return estadoAnterior; } public boolean esFinal(){ for(int i=0;i<estadoFinal.length;i++){ if(estadoFinal[i]==estado) return true; } return false; } public int tipoSimbolo( char simbolo){ ManejoCadena manejador= new ManejoCadena(); if(manejador.esLetra(simbolo)) return 1; else if(manejador.esNumero(simbolo)) return 0; return -1; } public int transicion(char simbolo){ ManejoCadena manejador= new ManejoCadena(); tipoSimbolo(simbolo); setEstadoAnterior(estado); switch (estado){ case 1: if(manejador.esLetra(simbolo)) setEstado(3); else if(manejador.esNumero(simbolo)) setEstado(2); else setEstado(-1);

Page 14: Reporte de Identificador Codigo

break; case 2: setEstado(-2); break; case 3: if(manejador.esLetra(simbolo)) setEstado(3); else if(manejador.esNumero(simbolo)) setEstado(3); else{ setEstado(-1); } break; } return getEstado(); }}

Page 15: Reporte de Identificador Codigo

package proyidentificador;

import java.util.regex.Matcher;import java.util.regex.Pattern;

public class ManejoCadena { Object objeto=new Object(); public boolean esLetra(char simbolo){ Pattern patronLetras = Pattern.compile("[A-Za-z]"); Matcher mLetras; objeto=simbolo; mLetras = patronLetras.matcher(objeto.toString()); if (mLetras.find()) return true; return false; } public boolean esNumero(char simbolo){ Pattern patronNumeros = Pattern.compile("[0-9]"); Matcher mNumeros; objeto=simbolo; mNumeros = patronNumeros.matcher(objeto.toString()); if (mNumeros.find()) return true; return false; } }

Page 16: Reporte de Identificador Codigo

/* * To change this template, choose Tools | Templates * and open the template in the editor. */package proyidentificador;

import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.io.PrintWriter;

/** * * @author JULIOC */public class ManejoArchivos {

public ManejoArchivos() { FileWriter fichero = null; PrintWriter pw = null; try { fichero = new FileWriter("C:/archivosNB/errores.txt"); pw = new PrintWriter(fichero); pw.print(-1); pw.println("error: caracter no aceptado"); pw.print(-2); pw.println("error: el primer caracter debes er una letra"); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != fichero) fichero.close(); } catch (Exception e2) { e2.printStackTrace(); }

Page 17: Reporte de Identificador Codigo

} }//fin del constructor public String obtenerTexto(int i){ File archivo = null; FileReader fr = null; BufferedReader br = null;

try { archivo = new File ("C:/archivosNB/errores.txt"); fr = new FileReader (archivo); br = new BufferedReader(fr); String linea; int numero; while((linea=br.readLine())!=null){ numero=Integer.parseInt(linea.substring(0, 2)); if(numero==i) return linea.substring(2); } } catch(Exception e){ e.printStackTrace(); }finally{ try{ if( null != fr ){ fr.close(); } }catch (Exception e2){ e2.printStackTrace(); } } return null; } }

Page 18: Reporte de Identificador Codigo

package proyidentificador;

/** * * @author JULIOC */public class ManejoErrores { String obtenerTexto(int i){ ManejoArchivos ma=new ManejoArchivos(); return ma.obtenerTexto(i); }}

Page 19: Reporte de Identificador Codigo

package proyidentificador;

import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.Timer;

/** * * @author JULIOC */public class Informacion extends javax.swing.JFrame {

/** * Creates new form Informacion */ public Informacion() { initComponents(); }

/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() {

jlbEscuela = new javax.swing.JLabel(); jlbCarrera = new javax.swing.JLabel(); jlbMateria = new javax.swing.JLabel(); jlbDescripcion = new javax.swing.JLabel(); jlbVersion = new javax.swing.JLabel(); jlbAutor = new javax.swing.JLabel(); jlbEmail = new javax.swing.JLabel(); jlbTel = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel();

Page 20: Reporte de Identificador Codigo

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jlbEscuela.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N jlbEscuela.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jlbEscuela.setText("INSTITUTO TECNOLOGICO DE CHILPANCINGO");

jlbCarrera.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N jlbCarrera.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jlbCarrera.setText("Ingenieria en sistemas computacionales");

jlbMateria.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jlbMateria.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jlbMateria.setText("Lenguajes y atómatas I");

jlbDescripcion.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jlbDescripcion.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jlbDescripcion.setText("Programa que evalua la estructura de un identificador para determinar si es válido o no.");

jlbVersion.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jlbVersion.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); jlbVersion.setText("Versión: 4.0");

jlbAutor.setText("Autor: julio Cesar Morales Gracia. ");

Page 21: Reporte de Identificador Codigo

jlbEmail.setText("e-mail:[email protected] ");

jlbTel.setText("Tel.7471334961");

jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/proyidentificador/logo - copia.jpg"))); // NOI18N

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jlbAutor)) .addGroup(layout.createSequentialGroup() .addGap(69, 69, 69) .addComponent(jlbEscuela, javax.swing.GroupLayout.PREFERRED_SIZE, 478, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap())

Page 22: Reporte de Identificador Codigo

.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jlbVersion, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jlbTel, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jlbEmail)) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jlbCarrera, javax.swing.GroupLayout.PREFERRED_SIZE, 330, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(162, 162, 162)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jlbMateria, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(195, 195, 195)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()

Page 23: Reporte de Identificador Codigo

.addComponent(jlbDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, 487, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(88, 88, 88)))))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(jlbEscuela, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jlbCarrera) .addGap(28, 28, 28) .addComponent(jlbMateria)) .addGroup(layout.createSequentialGroup() .addGap(31, 31, 31) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jlbDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jlbAutor, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

Page 24: Reporte de Identificador Codigo

.addComponent(jlbEmail) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlbTel) .addComponent(jlbVersion))) );

pack(); }// </editor-fold>

/** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Informacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) {

Page 25: Reporte de Identificador Codigo

java.util.logging.Logger.getLogger(Informacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Informacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Informacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold>

/* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { final Informacion info; info = new Informacion(); info.setVisible(true); Timer timer = new Timer (3000, new ActionListener () { public void actionPerformed(ActionEvent e) { info.dispose(); new InterfazIdentificador().setVisible(true); } });

timer.setRepeats(false);timer.start(); } }); } // Variables declaration - do not modify

Page 26: Reporte de Identificador Codigo

private javax.swing.JLabel jLabel1; private javax.swing.JLabel jlbAutor; private javax.swing.JLabel jlbCarrera; private javax.swing.JLabel jlbDescripcion; private javax.swing.JLabel jlbEmail; private javax.swing.JLabel jlbEscuela; private javax.swing.JLabel jlbMateria; private javax.swing.JLabel jlbTel; private javax.swing.JLabel jlbVersion; // End of variables declaration }

Page 27: Reporte de Identificador Codigo

package proyidentificador;

import java.awt.Color;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.util.TimerTask;import java.util.logging.Level;import java.util.logging.Logger;import javax.swing.JOptionPane;import javax.swing.Timer;

/** * * @author JULIOC */public class InterfazIdentificador extends javax.swing.JFrame {

/** * Creates new form InterfazIdentificador */ public InterfazIdentificador() { initComponents(); }

/** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() {

jplIntroducirDatos = new javax.swing.JPanel(); jlbIdentificador = new javax.swing.JLabel(); jtfIdentificador = new javax.swing.JTextField();

Page 28: Reporte de Identificador Codigo

jbnOk = new javax.swing.JButton(); jplProceso = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jtaProceso = new javax.swing.JTextArea(); jScrollPane2 = new javax.swing.JScrollPane(); jtpSalida = new javax.swing.JTextPane();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Evaluar Identificador");

jplIntroducirDatos.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

jlbIdentificador.setText("Identificador");

jtfIdentificador.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jtfIdentificadorKeyPressed(evt); } });

jbnOk.setText("OK"); jbnOk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbnOkActionPerformed(evt); } }); jbnOk.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jbnOkKeyPressed(evt); } });

javax.swing.GroupLayout jplIntroducirDatosLayout = new javax.swing.GroupLayout(jplIntroducirDatos);

Page 29: Reporte de Identificador Codigo

jplIntroducirDatos.setLayout(jplIntroducirDatosLayout); jplIntroducirDatosLayout.setHorizontalGroup( jplIntroducirDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jplIntroducirDatosLayout.createSequentialGroup() .addContainerGap() .addComponent(jlbIdentificador) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtfIdentificador, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbnOk) .addContainerGap(116, Short.MAX_VALUE)) ); jplIntroducirDatosLayout.setVerticalGroup( jplIntroducirDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jplIntroducirDatosLayout.createSequentialGroup() .addContainerGap() .addGroup(jplIntroducirDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlbIdentificador) .addComponent(jtfIdentificador, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jbnOk)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) );

Page 30: Reporte de Identificador Codigo

jplProceso.setBorder(new javax.swing.border.MatteBorder(null)); jplProceso.setToolTipText("");

jtaProceso.setEditable(false); jtaProceso.setColumns(20); jtaProceso.setForeground(new java.awt.Color(204, 0, 0)); jtaProceso.setRows(5); jtaProceso.setCaretColor(new java.awt.Color(204, 0, 0)); jtaProceso.setSelectedTextColor(new java.awt.Color(255, 0, 51)); jtaProceso.setSelectionColor(new java.awt.Color(102, 102, 255)); jScrollPane1.setViewportView(jtaProceso);

javax.swing.GroupLayout jplProcesoLayout = new javax.swing.GroupLayout(jplProceso); jplProceso.setLayout(jplProcesoLayout); jplProcesoLayout.setHorizontalGroup( jplProcesoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1) ); jplProcesoLayout.setVerticalGroup( jplProcesoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jplProcesoLayout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) );

jtpSalida.setEditable(false); jtpSalida.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jScrollPane2.setViewportView(jtpSalida);

Page 31: Reporte de Identificador Codigo

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jplIntroducirDatos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jplProceso, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane2)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(jplIntroducirDatos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jplProceso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

Page 32: Reporte de Identificador Codigo

.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) );

pack(); }// </editor-fold>

private void jbnOkActionPerformed(java.awt.event.ActionEvent evt) { try { // TODO add your handling code here: procesar(); } catch (Exception ex) { Logger.getLogger(InterfazIdentificador.class.getName()).log(Level.SEVERE, null, ex); } }

private void jbnOkKeyPressed(java.awt.event.KeyEvent evt) { // TODO add your handling code here: }

public void procesar() throws Exception{ // TODO add your handling code here: int i=0; int error=0; String cadena; String linea; int estadosFinales[]={3};

Page 33: Reporte de Identificador Codigo

Automata identificador= new Automata(1,estadosFinales); //u0020 cadena=jtfIdentificador.getText()+"@"; //jtaProceso.setSelectionColor(Color.red); jtaProceso.setText(null); jtaProceso.append("Iniciando análisis....\n"); jtaProceso.append("Cadena a analizar: \t"+cadena.substring(0,cadena.length()-1) +"\n"); jtaProceso.append("Estado inical: \t"+identificador.getEstadoInicial()+"\n\n"); //inicio /* Timer timer = new Timer (tiempoEnMilisegundos, new ActionListener () { public void actionPerformed(ActionEvent e) { // Aquí el código que queramos ejecutar. } }); timer.start(); */ //fin while(cadena.charAt(i)!='@'){ jtaProceso.append("Estado actual: \t"+identificador.getEstado()+"\n"); jtaProceso.append("Simbolo a analizar: \t"+cadena.charAt(i)+"\n"); if (identificador.tipoSimbolo(cadena.charAt(i))==1) jtaProceso.append(cadena.charAt(i)+": \tEs letra\n");

Page 34: Reporte de Identificador Codigo

else if(identificador.tipoSimbolo(cadena.charAt(i))==0) jtaProceso.append(cadena.charAt(i)+": \tEs Numero\n"); else jtaProceso.append(cadena.charAt(i)+": Es caracter no identificado\n"); error= identificador.transicion(cadena.charAt(i)); if(identificador.getEstado()>0){ jtaProceso.append("Cambiando del estado: \t"+identificador.getEstadoAnterior()+" "); jtaProceso.append("al estado: "+identificador.getEstado()+"\n\n\n"); } if(error<0) break; i++; if(cadena.charAt(i)=='@'){ jtaProceso.append("\n\nAnalizando fin de cadena \n"); jtaProceso.append(cadena.charAt(i)+": Es finde cadena\n"); } }//fin de cliclo while jtaProceso.append("\n\nFin de analisis \n"); jtaProceso.append("El ultimo estado es: "+identificador.getEstado()+"\n"); if(identificador.esFinal()) jtaProceso.append("Es final\n\n"); else jtaProceso.append("No es final\n\n"); if(error<0){ ManejoErrores me= new ManejoErrores();

Page 35: Reporte de Identificador Codigo

jtpSalida.setText(me.obtenerTexto(identificador.getEstado())); //System.out.println(me.obtenerTexto(identificador.getEstado())); } else if(identificador.esFinal()){ jtpSalida.setText("\ncadena aceptada."); //System.out.println("cadena aCeptada"); }else jtpSalida.setText("\n Cadena no aceptada."); } private void jtfIdentificadorKeyPressed(java.awt.event.KeyEvent evt) { // TODO add your handling code here: if(evt.getKeyCode()==KeyEvent.VK_ENTER){ try { procesar(); } catch (Exception ex) { Logger.getLogger(InterfazIdentificador.class.getName()).log(Level.SEVERE, null, ex); } } }

/** * @param args the command line arguments */ // Variables declaration - do not modify private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JButton jbnOk; private javax.swing.JLabel jlbIdentificador;

Page 36: Reporte de Identificador Codigo

private javax.swing.JPanel jplIntroducirDatos; private javax.swing.JPanel jplProceso; public static javax.swing.JTextArea jtaProceso; public static javax.swing.JTextField jtfIdentificador; private javax.swing.JTextPane jtpSalida; // End of variables declaration }

Page 37: Reporte de Identificador Codigo

Nombre: julio Cesar Morales García.

Ocupación: estudiante de la carrera de ingeniería en sistemas computacionales en el ITCH.

E-mail: [email protected]

Tel: 7471334961