Problema na alteração de tipo String para int

5 respostas
R

Pessoal, estou com o seguinte problema:

Digito em um campo formatado uma entrada que resulta neste valor 11.111.111/1111-11

Utilizo uma função (que tem como entrada o valor acima, e que retorna String) que remove os caracteres especiais, no caso retorna 11111111111111

String retorno = this.removeCaracEspeciais(entradaDados.getText().toString());

O problema está quando tento fazer a alteração de tipo String para int, como está na linha abaixo:

int retornoInt = Integer.parseInt( retorno);

Segue código completo abaixo:
Toda ajuda é bem vinda, vlw.

package projetotestemaskara;

import javax.swing.text.MaskFormatter;

/**
*

  • @author Ricardo
    */
    public class NewJFrame extends javax.swing.JFrame {

    /**

    • Creates new form NewJFrame
      */
      public NewJFrame() {
      initComponents();
      }
    @SuppressWarnings(unchecked)
    
    // 
    
    private void initComponents() {
    
    botaoProcessar = new javax.swing.JButton();
     saidaDados = new javax.swing.JLabel();
     entradaDados = new javax.swing.JFormattedTextField(setMascara("##.###.###/####-##"));
    
     setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
     botaoProcessar.setText("jButton1");
     botaoProcessar.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
             botaoProcessarActionPerformed(evt);
         }
     });
    
     saidaDados.setText("saida");
    
     entradaDados.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
             entradaDadosActionPerformed(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()
             .addGap(50, 50, 50)
             .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                 .addComponent(saidaDados, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                 .addComponent(entradaDados)
                 .addComponent(botaoProcessar, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE))
             .addContainerGap(184, Short.MAX_VALUE))
     );
     layout.setVerticalGroup(
         layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
             .addContainerGap(89, Short.MAX_VALUE)
             .addComponent(entradaDados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
             .addGap(46, 46, 46)
             .addComponent(botaoProcessar)
             .addGap(43, 43, 43)
             .addComponent(saidaDados)
             .addGap(65, 65, 65))
     );
    
     pack();
    

    }//

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

    private void botaoProcessarActionPerformed(java.awt.event.ActionEvent evt) {

    String retorno = this.removeCaracEspeciais(entradaDados.getText().toString());
     
      
      saidaDados.setText(retorno);
    
     
     int retornoInt = Integer.parseInt( retorno);
     
     System.out.println( retornoInt );
    

    }

    /**

    • @param args the command line arguments
      /
      public static void main(String args[]) {
      /

      • Set the Nimbus look and feel
        /
        //
        /
      • 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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //

      /*

      • Create and display the form
        */
        java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
        
        new NewJFrame().setVisible(true);
        
        }
        
        });
        
        }
        
        // Variables declaration - do not modify
        
        private javax.swing.JButton botaoProcessar;
        
        private javax.swing.JFormattedTextField entradaDados;
        
        private javax.swing.JLabel saidaDados;
        
        // End of variables declaration
        

    public MaskFormatter setMascara(String mascara){

    //para a aplicação no textField
    //# = qualquer numero válido
    //U = qualquer caractere, as letras minusculas são formatadas em maiuscula.
    //L = qualquer caractere, as letras maiusculas são formatadas em minusculas.
    //A = qualquer caractere ou numero.
    
    
    MaskFormatter mask = null;
    

    try{
    mask = new MaskFormatter(mascara);

    }catch(java.text.ParseException ex){}

    return mask;

    }

    public String removeCaracEspeciais(String str){

    //Troca os caracteres especiais da string por "" 
     String[] caracteresEspeciais = {"\\.", ",", "-", ":", "\\(", "\\)", "ª", "\\|", "\\\\", "°", "/"};
    
     for (int i = 0; i < caracteresEspeciais.length; i++) {
         str = str.replaceAll(caracteresEspeciais[i], "");
     }
    
     /** Troca os espaços no início por "" **/
     str = str.replaceAll("^\\s+", "");
     /** Troca os espaços no início por "" **/
     str = str.replaceAll("\\s+$", "");
     /** Troca os espaços duplicados, tabulações e etc por  " " **/
     str = str.replaceAll("\\s+", " ");
     
    
     return str;
    

    }

}

5 Respostas

al.barbosa

Ricardo,

Sugiro usar o botão Code para formatar o seu código. Veja abaixo:

http://www.guj.com.br/java/50115-voce-e-novo-no-guj-vai-criar-um-topico-e-colar-seu-codigo-fonte-leia-aqui-antes-por-favor

kadu.m.lino

qual é o erro?
tenta trocar int por Long

R

Alcebíades, o erro é o seguinte:

Exception in thread AWT-EventQueue-0 java.lang.NumberFormatException: For input string: 11111111111111at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

at java.lang.Integer.parseInt(Integer.java:495)

at java.lang.Integer.parseInt(Integer.java:527) e segue 

Ou seja minha variável retorno que é do tipo String não está sendo reconhecida como String quando á uso no procedimento na linha abaixo:

int retornoInt = Integer.parseInt( retorno);

kadu.m.lino

Cara, vc não vai conseguir alterar essa string pra int

int = 4 bytes - 32 bits = -[telefone removido] a + [telefone removido] - números inteiros

vc realmente precisa converter pra int? pq não deixar como string msm? ou mudar pra Long

R

É que preciso para inserir no banco do tipo inteiro, mas perante sua análise faz sentido, vou ter que tentar para Long.

Vlw

Criado 15 de junho de 2012
Ultima resposta 15 de jun. de 2012
Respostas 5
Participantes 3