Unexpected return when converting String to Integer in Java

Asked

Viewed 164 times

1

I have a java code in which you receive engine speed data. In java with I get a String I need to convert to integer to make a comparison to know if the engine started or not. When I get the string I print on the screen and it correctly appears the value, but in the dialog for the integer it only receives the value null, because the String is correct but when it converts me rtorna null, it has another way of conversation?

Follow the code:

package tanio;

import javax.swing.SwingWorker;

public class obterrpm extends SwingWorker {

    public SerialVirtualCom3 arduino6;
     String valorrpm;
     int valorrpmint;


    protected Object doInBackground() throws Exception {

         SerialVirtualCom3  arduino6 = new SerialVirtualCom3("COM3", 9600,0);

        arduino6.receberDados();



        while(true){
        delay.delay(300);
        valorrpm = arduino6.getPeso();
        //System.out.println(valorrpm); //printa o valor corretamente
        valorrpmint = Integer.parseInt(valorrpm); //conversao para o int

        System.out.println(valorrpmint); //retorno e null
        //chamarTelaPrincipal.rpm.setText(String.format("%s",arduino6.getPeso()));
        //chamarTelaPrincipal.rpm.setText(String.format("%s", valorrpmint));





    }



    }   
}

rotacao recebida do arduino rotacao no programa java com a variavel nao convertida

variavel convertida nao aparece nada

Serialvirtualcom3

package tanio;

import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.JOptionPane;
import javax.swing.SwingWorker;


public class SerialVirtualCom3  implements Runnable, SerialPortEventListener { 


    public String Dadoslidos; 

    public int nodeBytes; 

    private int baudrate; 

    private int timeout; 

    private CommPortIdentifier cp; 

    private SerialPort porta; 

    private OutputStream saida; 

    private InputStream entrada; 

    private Thread threadLeitura; 

    private boolean IDPortaOK;

    private boolean PortaOK; 

    private boolean Leitura; 

    private boolean Escrita;

    private String Porta; 

    protected String peso;

    public char valorlido;


    public void setPeso(String peso){

        this.peso = peso;

}



public String getPeso(){

        return peso;

}


public SerialVirtualCom3( String p , int b , int t ){

    this.Porta = p;

    this.baudrate = b;

    this.timeout = t;

}

public void HabilitarEscrita(){

    Escrita = true;

    Leitura = false;

}



public void HabilitarLeitura(){

    Escrita = false;

    Leitura = true;

}






///////////////////////////////////////////////////////
///*
public void ObterIdDaPorta(){

                try {
                cp = CommPortIdentifier.getPortIdentifier(Porta);

                if ( cp != null ) {

    //              System.out.println("Sucesso");


                    IDPortaOK = true; 

        //            ligado = 0;
            //        desligado = 1;

                }
                }

            /*
                IDPortaOK = false;
                ligado = 1;
                desligado = 0;
                //ligado = 1;
                //desligado = 0
                }
                */          
            catch (NoSuchPortException e) {

                e.printStackTrace();

                //System.out.println("Nao ha Conexao!");
              //  JOptionPane.showMessageDialog(null, "Houve um erro na Conexão!\nVerifique o cabo usb!");
                //teste de tratamento desta excessao

                //ligado = 1;
                //desligado = 0;
                //ObterIdDaPorta();
                //IDPortaOK = false;


            }
        }



//*/

//////////////////////////////////////////////////////

/*

public void ObterIdDaPorta(){

    boolean flag = false;

//  while (flag == false ){

        try {

        cp = CommPortIdentifier.getPortIdentifier(Porta);

        if ( cp == null ) {

            System.out.println("Erro na porta");

            IDPortaOK = false;
            JOptionPane.showMessageDialog(null, "Houve um erro na Conexão!\nVerifique o cabo usb!");
           // FecharCom();

            //ObterIdDaPorta();

            //System.exit(1);

        }

        IDPortaOK = true;
 //       flag = true;

    } catch (Exception e) {

        e.printStackTrace();
        //System.out.println("Erro obtendo ID da porta: " + e);

           JOptionPane.showMessageDialog(null, "Houve um erro na Conexão!\nVerifique o cabo usb!");
            //JOptionPane.showMessageDialog(null, "Houve um erro na Conexão!");
        IDPortaOK = false;
        //FecharCom();
        //flag = false;


        //ObterIdDaPorta();
        //System.exit(1);
    }
    }
  //  }
//}
//}



*/

/*
public void AbrirPorta(){

    try {


        porta = (SerialPort)cp.open("SerialComLeitura", timeout);

        PortaOK = true;

        //configurar parâmetros

        porta.setSerialPortParams(baudrate,

        porta.DATABITS_8,

        porta.STOPBITS_1,

        porta.PARITY_NONE);

        porta.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);

    }catch(Exception e){

        e.printStackTrace();
        //PortaOK = false;

        //System.out.println("Erro abrindo comunicação: " + e);
        JOptionPane.showMessageDialog(null, "Houve um erro na Conexão!\nVerifique o cabo usb!");
        FecharCom();

        //System.exit(1);

    }

}

*/







        public void AbrirPorta(){



               try {

                porta = (SerialPort)cp.open("SerialComLeitura", timeout);

                if (porta != null) {


                //configurar parâmetros

                porta.setSerialPortParams(baudrate,

                porta.DATABITS_8,

                porta.STOPBITS_1,

                porta.PARITY_NONE);

                porta.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);

              //  System.out.println("Sucesso no tratamento do erro de abrir porta!");

                PortaOK = true;



                }
    }
            catch(Exception e){


                e.printStackTrace();

                //System.out.println("houve um erro ao tratar a excessao do abrir porta!");
                //JOptionPane.showMessageDialog(null, "Houve um erro na Conexão!\nVerifique o cabo usb!");
                //teste de tratamento desta excessao

                //ligado = 1;
                //desligado = 0;
                //FecharCom();
                //ObterIdDaPorta();
                //AbrirPorta();

                //ObterIdDaPorta();
                //AbrirPorta();
                //IDPortaOK = false;


                /*
                e.printStackTrace();
                //PortaOK = false;

                //System.out.println("Erro abrindo comunicação: " + e);
                JOptionPane.showMessageDialog(null, "Houve um erro na Conexão!\nVerifique o cabo usb!");
                FecharCom();
                */
                //System.exit(1);

            }

        }






























public void LerDados(){

    if (Escrita == false){

        try {

            entrada = porta.getInputStream();

        } catch (Exception e) {
            e.printStackTrace();
             //System.out.println("Erro de stream: " + e);
            //JOptionPane.showMessageDialog(null, "Houve um erro na Conexão!\nVerifique o cabo usb!");
            //FecharCom();
            //AbrirPorta();
            //LerDados();
          //  System.exit(1);

        }

        try {

            porta.addEventListener(this);

        } catch (Exception e) {
            e.printStackTrace();

            //System.out.println("Erro de listener: " + e);
            //JOptionPane.showMessageDialog(null, "Houve um erro na Conexão!\nVerifique o cabo usb!");
            //FecharCom();
          //  AbrirPorta();
        //    LerDados();
            //System.exit(1);

        }

        porta.notifyOnDataAvailable(true);

        try {

            threadLeitura = new Thread(this);

            threadLeitura.start();

           run();

        } catch (Exception e) {
            e.printStackTrace();
            //System.out.println("Erro de Thred: " + e);
         //   JOptionPane.showMessageDialog(null, "Houve um erro na Conexão!\nVerifique o cabo usb!");
           // FecharCom();
            //AbrirPorta();
            //LerDados();
        }

    }

}

public void escrever(int msg){

    if (Escrita==true) {

        try {

            saida = porta.getOutputStream();

            //System.out.println("FLUXO OK!");

        } catch (Exception e) {
            e.printStackTrace();
           System.out.println("Erro.STATUS: " + e );
            //JOptionPane.showMessageDialog(null, "Houve um erro na Conexão!\nVerifique o cabo usb!\nReconecte o Cabo e Aguarde alguns segundos!");
            //FecharCom();

            //enviarDados(msg);
        }

        try {

            //System.out.println("Enviando um byte para " + Porta );

            //System.out.println("Enviando : " + msg );

            saida.write(msg);

            Thread.sleep(100);

            saida.flush();

        } catch (Exception e) {
            e.printStackTrace();
            //System.out.println("Houve um erro durante o envio. ");

            System.out.println("STATUS: " + e );
            //JOptionPane.showMessageDialog(null, "Houve um erro na Conexão!\nVerifique o cabo usb!");
            //FecharCom();
            //System.exit(1);

        }

    } else {

       // System.exit(1);
        //JOptionPane.showMessageDialog(null, "Houve um erro na Conexão!\nVerifique o cabo usb!");
        //FecharCom();
    }

}

public void run(){

    try {

        Thread.sleep(5);

    } catch (Exception e) {
        e.printStackTrace();

        //System.out.println("Erro de Thred: " + e);
        //JOptionPane.showMessageDialog(null, "Houve um erro na Conexão!\nVerifique o cabo usb!");
        //FecharCom(); 
        //run();
    }

}

public void serialEvent(SerialPortEvent ev){        

    StringBuffer bufferLeitura = new StringBuffer();

    int novoDado = 0;



    switch (ev.getEventType()) {

        case SerialPortEvent.BI:

        case SerialPortEvent.OE:

        case SerialPortEvent.FE:

        case SerialPortEvent.PE:

        case SerialPortEvent.CD:

        case SerialPortEvent.CTS:

        case SerialPortEvent.DSR:

        case SerialPortEvent.RI:

        case SerialPortEvent.OUTPUT_BUFFER_EMPTY:

        break;

        case SerialPortEvent.DATA_AVAILABLE:

            //Novo algoritmo de leitura.

            while(novoDado != -1){

                try{

                    novoDado = entrada.read();

                    if(novoDado == -1){

                        break;

                    }

                    if('\r' == (char)novoDado){

                        bufferLeitura.append('\n');

                    }else{

                        bufferLeitura.append((char)novoDado);

                    }

                }catch(IOException ioe){

                   // System.out.println("Erro de leitura serial: " + ioe);
          //          JOptionPane.showMessageDialog(null, "Houve um erro na Conexão!\nVerifique o cabo usb!");

                }

            }

            setPeso(new String(bufferLeitura));

            //System.out.println(getPeso());



        break;

    }

}

public void FecharCom(){

    try {

        porta.close();

    } catch (Exception e) {
        e.printStackTrace();
     //   System.out.println("Erro fechando porta: " + e);
      //  JOptionPane.showMessageDialog(null, "Houve um erro na Conexão!\nVerifique o cabo usb!");
       // FecharCom();
//        System.exit(0);

    }

}

public String obterPorta(){

    return Porta;

}



public int obterBaudrate(){

    return baudrate;

}



public void enviarDados(int msg)
{
    HabilitarEscrita();


    ObterIdDaPorta();

    AbrirPorta();

    escrever(msg);


    FecharCom();
}


String receberDados(){

    HabilitarLeitura();
    ObterIdDaPorta();
    AbrirPorta();
    LerDados();
    return getPeso();
}


}
  • 2

    It is not possible that the System.out.println(valorrpmint); show null. You can post your exit to take a look at it?

  • Victor, sorry, with null I meant that it does not return anything, the program runs but not the return if I use valorrpmint. with the variable without conversation, arduino6.getPeso(which is a string) the value is printed on the screen normally. Why will the empty result?

  • It shows zero?

  • No, nothing, in the normal output, with the variable value rpm, the value of the rpm is printed on the screen correctly, However with the value rpmint does not appear anything, it is only in this: WARNING: RXTX Version Mismatch Jar version = RXTX-2.2pre1 Native lib Version = RXTX-2.2pre2

  • Send us what your copy is showing. Give us a print (value) and send it to us.

  • 1

    Try moving the declaration from valorrpm and valorrpmint within the scope of the method doInBackground. Once done, to make sure that the integers and the string in question are matching print the following: System.out.printf("%s - String: %s, int: %d\n", Thread.currentThread().getName(), valorrpm, valorrpmint);.

  • If I put the two variable statements together in while one disturbs the other, for example, if I put value = arduino6.getPeso(); valorromint = Integer.parseint(valorrpm) nor the variable printa more

  • The same thing happened Anthony, I played for a thread and gave the following error: WARNING: RXTX Version Mismatch Jar version = RXTX-2.2pre1 Native lib Version = RXTX-2.2pre2 Exception in thread "Thread-0" java.lang.Numberformatexception: For input string: "750 " at java.lang.Numberformatexception.forInputString(Numberformatexception.java:65) at java.lang.Integer.parseint(Integer.java:580) at java.lang.Integer.parseint(Integer.java:615) at Tanio.RunObterRpm.run(Runobtenrpm.java:20) at java.lang.Thread.run(Thread.java:748) //It correctly receives the input value String

  • But can’t make conversation? Will it be why? need to convert to compare the rpm value to know if the engine started, if (value rpmint > 0 ){car started}Else{car not started}, have cmo make this comparison without converting?

  • "750 ". Looks like there’s a blank spot at the end of your String. Try to use Integer.parseInt(valorrpm.trim()); If it works, I’ll turn it into an answer.

  • Anthony, I tried but gave Exception in thread "Thread-0" java.lang.Nullpointerexception at Tanio.RunObterRpm.run(Runobtenrpm.java:20) at java.lang.Thread.run(Thread.java:748)?

  • You could include the class code SerialVirtualCom3?

  • Weslley ta ai, disregard some parts that are among the /*, I was trying to treat the excesses but ended up giving up

  • Try setting your variable peso in a new String. Something like String str = arduino6.getPeso();. After that, throw the str in output.

  • But that’s not what I’m already doing with String valorrpm = arduino6.getPeso(); I don’t mean because this conversation doesn’t work, or when it looks like it will work from the excesses. I’m thinking I should then have to in the buffer read method to return me the integer instead of the string

Show 10 more comments

1 answer

0

Just replace '%s' with '%d'.

%s is for Strings printing and%d is for integer printing.

chamarTelaPrincipal.rpm.setText(String.format("%d", valorrpmint));
  • If I explain why I think the answer would be better and complete.

  • 1

    Thanks for the suggestion.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.