Home > Software engineering >  java.lang.NumberFormatException: For input string: "5.3"
java.lang.NumberFormatException: For input string: "5.3"

Time:05-26

when running this code i am getting this java.lang.NumberFormatException: For input string: "5.3" Exception. how can we resolve this type of exception.any other way we can handle this without try and catch? value can be any thing.it's not fixed that it will always be float.it can be integer and double too.is there any way we can handle all three no matter what comes .without using try catch.

passing this in line 79 PreferenceConstants.DEVICE_LAST_ERROR_CODE

 public static final String DEVICE_LAST_ERROR_CODE = "device_last_error_code";

please find the code below.

package com.pds.ftp.view.activity;

import android.content.res.Configuration;
import android.os.Bundle;

import androidx.annotation.NonNull;

import com.pds.ftp.R;
import com.pds.ftp.app.FTPApp;
import com.pds.ftp.constant.UIConstant;
import com.pds.ftp.infrastructure.ReaderUsbInterf;
import com.pds.ftp.middleware.FTPPrivilegedServiceProvider;
import com.pds.ftp.middleware.PollingLooperThread;
import com.pds.ftp.middleware.ShutDownManager;
import com.pds.ftp.model.dbsync.DBSynchronizationPool;
import com.pds.ftp.transaction.shutdown.EntryExitCheck;
import com.pds.ftp.transaction.shutdown.ShutdownStateCache;
import com.pds.ftp.utils.Util;
import com.pds.hardwareadapter.ingenicoreader.IngenicoReaderDirect;
import com.pds.infrastructure.constants.PreferenceConstants;
import com.pds.infrastructure.interfaces.ILogOperation;
import com.pds.infrastructure.logger.LogCriticalEvent;
import com.pds.infrastructure.logger.LogInfoEvent;
import com.pds.infrastructure.logger.LogWarningEvent;

import javax.inject.Inject;

public class PowerOffActivity extends BaseActivity {

    public static final String TYPE = "action_type";
    public static final int TYPE_SHUTDOWN = 0;
    public static final int TYPE_RESTART = 1;
    public static final int TYPE_END_OF_BUSINESS_HOURS = 2;
    public static final int SHUTDOWN_DELAY = 1000 * 30;
    public static final int SHUTDOWN_WAIT = 1000;
    public static final int READER_REBOOT = 3;

    @Inject
    ILogOperation logOperation;

    @Inject
    EntryExitCheck entryExitCheck;

    @Inject
    ShutdownStateCache shutdownStateCache;

    @Inject
    IngenicoReaderDirect ingenicoReaderDirect;

    @Inject
    PollingLooperThread pollingLooperThread;

    @Inject
    ReaderUsbInterf usbInterf;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        isShutDownRequestInitiated = true;
        setContentView(R.layout.activity_power_off);

        shutdownStateCache.setShutdownState(true); //Shutdown state is true as power is disconnected
        logOperation.logInfo(LogInfoEvent.GENERAL_INFO, "PowerOff Screen Started");

    }

    boolean keepOnRunning = true;

    private void checkForPendingTaskBeforeShutdown() {
        keepOnRunning = true;
        long startTime = System.currentTimeMillis();
        new Thread(new Runnable() {
            @Override
            public void run() {
                pollingLooperThread.onpause();
                if (getIntent() != null) {
                    int type = getIntent().getIntExtra(TYPE, 0);
                    int currentErrorCode = Integer.parseInt(configParams.getString(PreferenceConstants.DEVICE_LAST_ERROR_CODE));
                    int restartCount = configParams.getInt(PreferenceConstants.PREF_FTP_RESTART_COUNT);
                    if (type == TYPE_END_OF_BUSINESS_HOURS || (currentErrorCode == LogCriticalEvent.CARD_READER_MALFUNCTION && restartCount == 1)) {
                        logOperation.logInfo(LogInfoEvent.GENERAL_INFO, "Calling reader reset command due to EOB or CARD_READER_MALFUNCTION. currentErrorCode:: " currentErrorCode);
                        try {
                            Thread.sleep(3500);
                        } catch (Exception e) {
                            logOperation.logVerbose(LogInfoEvent.GENERAL_INFO, e,"Exception caused in Thread.sleep during reset reader");
                        }
                        ingenicoReaderDirect.resetReader();
                    }
                } else{
                    logOperation.logInfo(LogInfoEvent.GENERAL_INFO, "getIntent() is null");
                }

                while (keepOnRunning) {

                    if (entryExitCheck.getShutDownDBTaskCounter() == 0) {
                        logOperation.logVerbose(LogInfoEvent.GENERAL_INFO, "All threads are completed");
                        keepOnRunning = false;
                    } else {
                        if ((System.currentTimeMillis() - startTime) >= SHUTDOWN_DELAY) {
                            logOperation.logVerbose(LogInfoEvent.GENERAL_INFO, "Time exceeds 30 sec,initiating shutdown");
                            keepOnRunning = false;
                        } else {
                            logOperation.logVerbose(LogInfoEvent.GENERAL_INFO, "Threads still running");
                        }
                    }
                    try {
                        Thread.sleep(SHUTDOWN_WAIT);
                    } catch (Exception e) {
                        logOperation.logInfo(LogInfoEvent.GENERAL_INFO,e,"checkForPendingTaskBeforeShutdown Exception");
                    }
                }

                performShutdownProcess();
            }
        }).start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkForPendingTaskBeforeShutdown();
    }

    private void performShutdownProcess() {
        if (!Util.shutdown_file_available()) {
            FTPApp.isShuttingDownState = true;
            Util.setLastShutDownDateTime(configParams);
            if (getIntent() != null) {
                int type = getIntent().getIntExtra(TYPE, 0);
                String state = getIntent().getStringExtra(UIConstant.UISTATE);

                if (type == TYPE_END_OF_BUSINESS_HOURS) {
                    logOperation.logWarning(LogWarningEvent.DEVICE_SCHEDULED_OUT_OF_SERVICE, 2, "Device restarting because of end of business hours");
                }

                /*if (state.contains(UIConstant.IGNITION_OFF)) {
                    FTPApp.isShuttingDownState = true;
                }*/

                if (type == TYPE_RESTART || type == TYPE_END_OF_BUSINESS_HOURS|| type == READER_REBOOT) {
                    logOperation.logWarning(LogWarningEvent.DEVICE_REBOOTED, "Device is RESTARTING.. Coming from:- "   state);
                } else {
                    logOperation.logWarning(LogWarningEvent.DEVICE_SHUT_DOWN, "Device is shutting down Reason:- IGNITION... Coming From:- "   state);
                }
            } else {
                logOperation.logWarning(LogWarningEvent.DEVICE_REBOOTED, "Device is RESTARTING. Reason:- OTHER");
            }
            usbInterf.close();
            ShutDownManager.getInstance().shutDownDevice();
        }
    }

    @Override
    void prepareTextToSpeechAndSpeak() {
    }


    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

    }
}

getting this in logs it looks like this exception is coming from line 79

4,0,05.16.2022_09.09.00.822,java.lang.NumberFormatException: For input string: "5.3"
java.lang.Integer.parseInt(Integer.java:608)
java.lang.Integer.parseInt(Integer.java:643)
com.pds.ftp.view.activity.PowerOffActivity$1.run(PowerOffActivity.java:79)
java.lang.Thread.run(Thread.java:764)
Line 8922: 2,1000,05.16.2022_09.09.00.910,Info,Current Error Code = 0

CodePudding user response:

any other way we can handle this without try and catch?

You need to parse it with the right parse method so that the exception is not thrown.

value can be any thing.

Well if that is literally true, it means that you cannot parse it, except the most trivial sense.

it's not fixed that it will always be float.it can be integer and double too.

Ah ... so when you said "any thing" you didn't mean anything?

There are three possible ways to handle this:

  1. Just read the error code as a string, and don't attempt to parse it.

    Ask yourself: do you actually need to treat the error code as a number? What does that buy you? And what if the error code isn't a recognizable number at all? (Will your application be able to cope?)

  2. Parse the error code using parseDouble, and represent it as a double. The syntax parsed by parseDouble is the same as for parseFloat and a superset of what is accepted by parseInt. Specifically, parseDouble will happily parse an integer value ... and give you the double representation of that integer.

    The downside is that for large enough integers, the double representation will be imprecise / inaccurate. Depending on the actual code values, this might cause problems.

  3. If you must parse it with the right type then the way you avoid try / catch would be to use Pattern to implement regexes to test which of the expected formats the error code is in. Then call the corresponding parseXXX method to parse it.

    The downside is that you now need three (or more) different variables with types int, float, double and so on to represent the parsed error code values. And all of the places where you used the error code later in your application will have to deal with that.

  4. And of course, you could just use a sequence try-catches.

CodePudding user response:

The line in question is

int currentErrorCode = Integer.parseInt(configParams.getString(PreferenceConstants.DEVICE_LAST_ERROR_CODE));

this parses an integer, not a float; it expects a string representation of an integer. 5.3 is not an integer and contains a decimal point, causing the NumberFormatException. Use Float.parseFloat or Double.parseDouble instead; depending on your use case, you might want to round the result to an int.

  • Related