[Array][String] "Criptografia" simples

8 respostas
Revoke

Pessoal to precisando de uma ajuda nessa, to desenvolvendo um programinha besta, que pega um texto e "criptografa" ele para outro texto, cada letra tem uma correspondente nesse novo alfabeto, entendem ? Problema eah que para uma letra ele funciona perfeitamente, quando coloco mais coisas escritas, ele so imprime a correspondente da ultima, e eu nao consegui entender o porque.

O codigo eah o seguinte

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.Iterator;


public class Cadastro extends JFrame 
{
    
    private JLabel lbEntrada, lbSaida;
    private JTextArea txtEntrada, txtSaida;
    private JButton btnTraduzir;
    private JScrollPane srcPane;

    public Cadastro() {
        super("Traduzir");
        Container tela = getContentPane();
        tela.setLayout(new FlowLayout());

        lbEntrada = new JLabel("Entrada");
        lbSaida = new JLabel("Saida");

        lbEntrada.setBounds(10, 10, 300, 15);
        lbSaida.setBounds(40, 160,240,15);

        lbEntrada.setForeground(Color.BLACK);
        lbSaida.setForeground(Color.BLACK);

        lbEntrada.setFont(new Font("Courier New", Font.BOLD, 14));
        lbSaida.setFont(new Font("Courier New", Font.BOLD, 14));

        tela.add(lbEntrada);
        txtEntrada = new JTextArea(5,30);
        tela.add(txtEntrada);
        tela.add(lbSaida);

        
        txtSaida = new JTextArea(5,30);
        //srcPane = new JScrollPane(txtEntrada,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
        //JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        
        //txtEntrada.setBounds(10,25,300,20);
        //txtSaida.setBounds(10,150,300,20);
        txtSaida.setEditable(false);
        
        
        tela.add(txtSaida);
        
        btnTraduzir = new JButton("Traduzir");
        
        btnTraduzir.setBounds(320, 25, 100, 20);
        
        tela.add(btnTraduzir);
        
        setSize(450, 400);
        setVisible(true);
        setLocationRelativeTo(null);
        
        btnTraduzir.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        onTraduzir();
                    }

            private void onTraduzir() {
                int i;
                ArrayList texto = new ArrayList();
                String text = txtEntrada.getText();
                
                for(i=0; i<=text.length(); i++){
                    if("a".equals(text.substring(i))){
                        texto.add(new Character('3'));
                    }
                    else if("b".equals(text.substring(i))){
                        texto.add(new Character('r'));
                    }
                    else if("c".equals(text.substring(i))){
                        texto.add(new Character('q'));
                    }
                    else if("d".equals(text.substring(i))){
                        texto.add(new Character('z'));
                    }
                    else if("e".equals(text.substring(i))){
                        texto.add(new Character('0'));
                    }
                    else if("f".equals(text.substring(i))){
                        texto.add(new Character('s'));
                    }
                    else if("g".equals(text.substring(i))){
                        texto.add(new Character(' '));
                    }
                    else if("h".equals(text.substring(i))){
                        texto.add(new Character('l'));
                    }
                    else if("i".equals(text.substring(i))){
                        texto.add(new Character('7'));
                    }
                    else if("j".equals(text.substring(i))){
                        texto.add(new Character('b'));
                    }
                    else if("k".equals(text.substring(i))){
                        texto.add(new Character('n'));
                    }
                    else if("l".equals(text.substring(i))){
                        texto.add(new Character('a'));
                    }
                    else if("m".equals(text.substring(i))){
                        texto.add(new Character('9'));
                    }
                    else if("n".equals(text.substring(i))){
                        texto.add(new Character('g'));
                    }
                    else if("o".equals(text.substring(i))){
                        texto.add(new Character('2'));
                    }
                    else if("p".equals(text.substring(i))){
                        texto.add(new Character('c'));
                    }
                    else if("q".equals(text.substring(i))){
                        texto.add(new Character('i'));
                    }
                    else if("r".equals(text.substring(i))){
                        texto.add(new Character('8'));
                    }
                    else if("s".equals(text.substring(i))){
                        texto.add(new Character('6'));
                    }
                    else if("t".equals(text.substring(i))){
                        texto.add(new Character('4'));
                    }
                    else if("u".equals(text.substring(i))){
                        texto.add(new Character('5'));
                    }
                    else if("v".equals(text.substring(i))){
                        texto.add(new Character('m'));
                    }
                    else if("x".equals(text.substring(i))){
                        texto.add(new Character('e'));
                    }
                    else if("w".equals(text.substring(i))){
                        texto.add(new Character('o'));
                    }
                    else if("y".equals(text.substring(i))){
                        texto.add(new Character('t'));
                    }
                    else if("z".equals(text.substring(i))){
                        texto.add(new Character('k'));
                    }
                    else if(" ".equals(text.substring(i))){
                        texto.add(i,new Character('1'));
                    }
                }
                char[] valor = new char[texto.size()];
                int n=0;
                for(Iterator iter = texto.iterator(); iter.hasNext(); n++) 
                {  
                 valor[n] = ((Character)iter.next()).charValue();  
                
                }
                String str = new String(valor);
                
                txtSaida.setText(str);
            }
                }
        );
    
    }
}

8 Respostas

rmendes08

O problema é o uso do método substring, esse tá atrapalhando sua vida. Eu sugiro o seguinte, faça a comparação com caracteres mesmo, use o método charAt(i). Para comparar você usa as constantes de caracteres e o sinal ==, assim:

if( 'a' == text.getCharAt(i) ){
 //...
}

E minha segunda sugestão é você usar um StringBuilder ao invés de um ArrayList. Nesse caso, ao invés de usar chamar o método add você usa o método append.

E já que você gosta de criptografia entenda o que você está fazendo:

Revoke

Ele nao deixa eu usar esse jeito que vc falou, da cannot find symbol
symbol: getCharAt(int)
location: variable text of type java.lang.String

Vou dar uma pesquisada em StringBuilder tb! Se so mudar isso vai ser facil de usar …

E vlw a dica!

pmlm

É simplesmente charAt, não tem o get.

E em vez de teres todos esses ifs porque não crias dois arrays? Um com os caracteres originais outro com os caracteres cifrados.

ViniGodoy

Outras dicas:

  1. Não tem porque não definir o tipo do seu ArrayList:
List&lt;Character&gt; texto = new ArrayList&lt;Character&gt;();
  1. Não tem porque usar o iterator diretamente, use o list:

for (Character ch : texto) { valor[n] = ch.charValue(); n += 1; }

  1. Melhor do que o ArrayList seria usar um StringBuider;

  2. Já que você pode usar collections, siga a sugestão do colega anterior usando um Map<Character, Character>

pmlm

Também pensei no map mas este só é útil se for somente para criptografar. Eu já estava a pensar mais à frente e em implementar também a descriptografia.

fernandosavio
public class MainTeste {

	public static void main(String args[]){
		String pal = "palavra";
		System.out.println(encripta(pal));
	}

	public static String encripta(String palavra){
		//"Tabela" com os chars critografados
		char[] tabela = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
		//letras onde serão pesquisados os chars
		String cru = "abcdefghijklmnopqrstuvwxyz";
		//variável que guardará o resultado
		StringBuilder sb = new StringBuilder();
		for(int i=0 ; i<palavra.length() ; i++){
			char c = palavra.charAt(i);//Letra atual
			int nLetra = cru.indexOf(c);//Posição da letra no alfabeto e na tabela
			sb.append(tabela[nLetra]);
		}
		return sb.toString();
	}
}

Assim tem bem menos if’s…

Revoke

Muito obrigado a todos os replies!!
Fiz algumas alterações. Bem, o charAt(i) no codigo original nao funcionou....

Com a ultima sugestao o codigo ficou assim, mas ainda assim ele nao funciona, deste modo alias ele nao criptografa nada, da uma serie de erros, sendo estes os principais

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
at primeirodesetembro.Cadastro$1.encripta(Cadastro.java:96)
at primeirodesetembro.Cadastro$1.onTraduzir(Cadastro.java:83)
at primeirodesetembro.Cadastro$1.actionPerformed(Cadastro.java:76)

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.FlowLayout;
import java.util.ArrayList;
//import java.util.Iterator;


public class Criptografa extends JFrame 
{
    
    private JLabel lbEntrada, lbSaida;
    private JTextArea txtEntrada, txtSaida;
    private JButton btnTraduzir;
    private JScrollPane srcPane;

    public Criptografa() {
        super("Traduzir");
        Container tela = getContentPane();
        tela.setLayout(new FlowLayout());

        lbEntrada = new JLabel("Entrada");
        lbSaida = new JLabel("Saida");

        lbEntrada.setBounds(10, 10, 300, 15);
        lbSaida.setBounds(40, 160,240,15);

        lbEntrada.setForeground(Color.BLACK);
        lbSaida.setForeground(Color.BLACK);

        lbEntrada.setFont(new Font("Courier New", Font.BOLD, 14));
        lbSaida.setFont(new Font("Courier New", Font.BOLD, 14));

        tela.add(lbEntrada);
        txtEntrada = new JTextArea(5,30);
        tela.add(txtEntrada);
        tela.add(lbSaida);

        
        txtSaida = new JTextArea(5,30);
        //srcPane = new JScrollPane(txtEntrada,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
        //JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        
        //txtEntrada.setBounds(10,25,300,20);
        //txtSaida.setBounds(10,150,300,20);
        txtSaida.setEditable(false);
        
        
        tela.add(txtSaida);
        
        btnTraduzir = new JButton("Traduzir");
        
        btnTraduzir.setBounds(320, 25, 100, 20);
        
        tela.add(btnTraduzir);
        
        setSize(450, 400);
        setVisible(true);
        setLocationRelativeTo(null);
        
        btnTraduzir.addActionListener(
                new ActionListener() {
            @Override
                    public void actionPerformed(ActionEvent e) {
                        onTraduzir();
                    }

            private void onTraduzir() {
                //int i;
                //ArrayList<Character> texto = new ArrayList<Character>();
                String text = txtEntrada.getText();
                txtSaida.setText(encripta(text));
                        
            }
                public String encripta(String palavra){  
                //"Tabela" com os chars critografados  
                char[] tabela = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};  
                //letras onde serão pesquisados os chars  
                String cru = "abcdefghijklmnopqrstuvwxyz";  
                //variável que guardará o resultado  
                StringBuilder sb = new StringBuilder();  
                for(int i=0 ; i<palavra.length() ; i++){  
                    char c = palavra.charAt(i);//Letra atual  
                    int nLetra = cru.indexOf(c);//Posição da letra no alfabeto e na tabela  
                    sb.append(tabela[nLetra]);  
                }  
                return sb.toString();  
            }
                }
                );
                
}
}
fernandosavio

java.lang.ArrayIndexOutOfBoundsException: -1
Você está tentando acessar um índice fora dos limites do vetor…
O código que eu te passei está funcionando…
Debuga e vê que palavra está sendo passada…

Criado 7 de setembro de 2011
Ultima resposta 8 de set. de 2011
Respostas 8
Participantes 5