Como fazer um automato em Java
Publicado por Tiago Alves de Oliveira (última atualização em 29/09/2009)
[ Hits: 14.381 ]
Esse exemplo mostra como criar um automato em Java. O automato implementado é um reconhecedor de números romanos até 100. Comentem por favor.
/*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; } }
Exemplo básico da biblioteca Swing
Nenhum comentário foi encontrado.
Passkeys: A Evolução da Autenticação Digital
Instalação de distro Linux em computadores, netbooks, etc, em rede com o Clonezilla
Título: Descobrindo o IP externo da VPN no Linux
Armazenando a senha de sua carteira Bitcoin de forma segura no Linux
Enviar mensagem ao usuário trabalhando com as opções do php.ini
Instalando Brave Browser no Linux Mint 22
vídeo pra quem quer saber como funciona Proteção de Memória:
Encontre seus arquivos facilmente com o Drill
Mouse Logitech MX Ergo Advanced Wireless Trackball no Linux
Compartilhamento de Rede com samba em modo Público/Anônimo de forma simples, rápido e fácil
VMs e Interfaces de Rede desapareceram (11)
Instalação do drive do adaptador wiffi (7)