Como fazer um automato em Java

Publicado por Tiago Alves de Oliveira (última atualização em 29/09/2009)

[ Hits: 14.270 ]

Download Principal.java




Esse exemplo mostra como criar um automato em Java. O automato implementado é um reconhecedor de números romanos até 100. Comentem por favor.

  



Esconder código-fonte

/*Classe Principal*/
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Principal.java
 *
 * Created on 25/09/2009, 18:31:13
 */

package automato;

import javax.swing.JOptionPane;

/**
 *
 * @author tiago
 */
public class Principal extends javax.swing.JFrame {
    //Estados Aceitáveis
    int estadoaceitaveis[] ={2,3,4,5,6,7,8,9,10,11,12,13,14,15};

    /** Creates new form Principal */
    public Principal() {
        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">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Palavra Teste:");

        jTextField1.setToolTipText("Entre com a sequência a ser testada");

        jButton1.setText("Verifica");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(87, 87, 87)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addContainerGap(20, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        Automato aut = new Automato(jTextField1.getText());//instanciando os objetos
        aut.calcula();//calculando
        int finalizado = aut.getEstado();//pegando o estado final do automato
        boolean teste=false;//testando o estado final
        for (int aux=0;aux <estadoaceitaveis.length;aux++){
            if(finalizado==estadoaceitaveis[aux]){
                teste = true;//Se estado eh igual ao final teste recebe true
            }
        }
        if (teste){//SE o teste é válido
            JOptionPane.showMessageDialog(null, "Palavra Válida");
        }else JOptionPane.showMessageDialog(null, "Palavra Inválida");
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Principal().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables

}

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

/*Classe Automato*/
/**
 *
 * @author tiago
 */
public class Automato {

    String palavra;
    static int estado;
    char letra;
    char[] alfabeto = {'I', 'V', 'X', 'L', 'C'};

    public Automato(String palavra) {
        this.palavra = palavra;
    }

    public void calcula() {
        boolean estaAlfabeto = true;
        estado = 1;//estado Inicial
        for (int i = 0; i < palavra.length(); i++) {//Andando na palavra
            letra = palavra.charAt(i);//letra recebendo um caracter da palavra
            estaAlfabeto = false;
            for (int aux = 0; aux < alfabeto.length; aux++) {
                if (letra == alfabeto[aux])//verificando se ta no alfabeto
                {
                    estaAlfabeto = true;
                }
            }
            if (estaAlfabeto) {//se esta no alfabeto
                switch (estado) {//pegando os estados
                    case 1: {
                        if (letra == 'I') {
                            estado = 2;
                        } else if (letra == 'V') {
                            estado = 5;
                        } else if (letra == 'X') {
                            estado = 8;
                        } else if (letra == 'L') {
                            estado = 11;
                        } else if (letra == 'C') {
                            estado = 13;
                        } else {
                            estado = 0;
                        }
                        break;
                    }
                    case 2: {
                        if (letra == 'I') {
                            estado = 3;
                        } else if (letra == 'V') {
                            estado = 6;
                        } else if (letra == 'X') {
                            estado = 14;
                        } else if (letra == 'L') {
                            estado = 0;
                        } else if (letra == 'C') {
                            estado = 0;
                        } else {
                            estado = 0;
                        }
                        break;
                    }
                    case 3: {
                        if (letra == 'I') {
                            estado = 4;
                        } else if (letra == 'V') {
                            estado = 0;
                        } else if (letra == 'X') {
                            estado = 0;
                        } else if (letra == 'L') {
                            estado = 0;
                        } else if (letra == 'C') {
                            estado = 0;
                        } else {
                            estado = 0;
                        }
                        break;
                    }
                    case 4: {
                        if (letra == 'I') {
                            estado = 0;
                        } else if (letra == 'V') {
                            estado = 0;
                        } else if (letra == 'X') {
                            estado = 0;
                        } else if (letra == 'L') {
                            estado = 0;
                        } else if (letra == 'C') {
                            estado = 0;
                        } else {
                            estado = 0;
                        }
                        break;
                    }
                    case 5: {
                        if (letra == 'I') {
                            estado = 7;
                        } else if (letra == 'V') {
                            estado = 0;
                        } else if (letra == 'X') {
                            estado = 0;
                        } else if (letra == 'L') {
                            estado = 0;
                        } else if (letra == 'C') {
                            estado = 0;
                        } else {
                            estado = 0;
                        }
                        break;
                    }
                    case 6: {
                        if (letra == 'I') {
                            estado = 0;
                        } else if (letra == 'V') {
                            estado = 0;
                        } else if (letra == 'X') {
                            estado = 0;
                        } else if (letra == 'L') {
                            estado = 0;
                        } else if (letra == 'C') {
                            estado = 0;
                        } else {
                            estado = 0;
                        }
                        break;
                    }
                    case 7: {
                        if (letra == 'I') {
                            estado = 3;
                        } else if (letra == 'V') {
                            estado = 0;
                        } else if (letra == 'X') {
                            estado = 0;
                        } else if (letra == 'L') {
                            estado = 0;
                        } else if (letra == 'C') {
                            estado = 0;
                        } else {
                            estado = 0;
                        }
                        break;
                    }
                    case 8: {
                        if (letra == 'I') {
                            estado = 2;
                        } else if (letra == 'V') {
                            estado = 5;
                        } else if (letra == 'X') {
                            estado = 9;
                        } else if (letra == 'L') {
                            estado = 12;
                        } else if (letra == 'C') {
                            estado = 0;
                        } else {
                            estado = 0;
                        }
                        break;
                    }
                    case 9: {
                        if (letra == 'I') {
                            estado = 2;
                        } else if (letra == 'V') {
                            estado = 5;
                        } else if (letra == 'X') {
                            estado = 10;
                        } else if (letra == 'L') {
                            estado = 0;
                        } else if (letra == 'C') {
                            estado = 0;
                        } else {
                            estado = 0;
                        }
                        break;
                    }
                    case 10: {
                        if (letra == 'I') {
                            estado = 2;
                        } else if (letra == 'V') {
                            estado = 5;
                        } else if (letra == 'X') {
                            estado = 0;
                        } else if (letra == 'L') {
                            estado = 0;
                        } else if (letra == 'C') {
                            estado = 0;
                        } else {
                            estado = 0;
                        }
                        break;
                    }
                    case 11: {
                        if (letra == 'I') {
                            estado = 2;
                        } else if (letra == 'V') {
                            estado = 5;
                        } else if (letra == 'X') {
                            estado = 8;
                        } else if (letra == 'L') {
                            estado = 0;
                        } else if (letra == 'C') {
                            estado = 0;
                        } else {
                            estado = 0;
                        }
                        break;
                    }
                    case 12: {
                        if (letra == 'I') {
                            estado = 2;
                        } else if (letra == 'V') {
                            estado = 5;
                        } else if (letra == 'X') {
                            estado = 0;
                        } else if (letra == 'L') {
                            estado = 0;
                        } else if (letra == 'C') {
                            estado = 0;
                        } else {
                            estado = 0;
                        }
                        break;
                    }
                    case 13: {
                        if (letra == 'I') {
                            estado = 0;
                        } else if (letra == 'V') {
                            estado = 0;
                        } else if (letra == 'X') {
                            estado = 0;
                        } else if (letra == 'L') {
                            estado = 0;
                        } else if (letra == 'C') {
                            estado = 0;
                        } else {
                            estado = 0;
                        }
                        break;
                    }
                    case 14: {
                        if (letra == 'I') {
                            estado = 0;
                        } else if (letra == 'V') {
                            estado = 0;
                        } else if (letra == 'X') {
                            estado = 0;
                        } else if (letra == 'L') {
                            estado = 0;
                        } else if (letra == 'C') {
                            estado = 0;
                        } else {
                            estado = 0;
                        }
                        break;
                    }  case 15: {
                        if (letra == 'I') {
                            estado = 2;
                        } else if (letra == 'V') {
                            estado = 5;
                        } else if (letra == 'X') {
                            estado = 0;
                        } else if (letra == 'L') {
                            estado = 0;
                        } else if (letra == 'C') {
                            estado = 0;
                        } else {
                            estado = 0;
                        }
                        break;
                    }
                    default: {
                        estado = 0;
                        break;
                    }
                }
            } else {
                estado = 0; //estado de erro
            }
        }
    }

    //Metodos Getters e Setters

    public char[] getAlfabeto() {
        return alfabeto;
    }

    public void setAlfabeto(char[] alfabeto) {
        this.alfabeto = alfabeto;
    }

    public int getEstado() {
        return estado;
    }

    public void setEstado(int estado) {
        this.estado = estado;
    }

    public char getLetra() {
        return letra;
    }

    public void setLetra(char letra) {
        this.letra = letra;
    }

    public String getPalavra() {
        return palavra;
    }

    public void setPalavra(String palavra) {
        this.palavra = palavra;
    }
}


Scripts recomendados

Uso de enum em Java

Calculando a Media

Começando a trabalhar com arrays

Exemplo de Locadora de Veículos

Comando for


  

Comentários

Nenhum comentário foi encontrado.


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts