java.lang.NumberFormatException:对于输入字符串:“5.3”

java.lang.NumberFormatException: For input string: "5.3"

当 运行 我收到此代码时 java.lang.NumberFormatException:对于输入字符串:“5.3”异常。我们如何解决这种类型的 exception.any 我们可以不用 try and catch 来处理这个问题?值可以是任何 thing.it 不固定,它永远是 float.it 可以是整数和双精度 too.is 无论发生什么,我们都可以处理这三个。不使用 try catch .

在第 79 行传递这个 PreferenceConstants.DEVICE_LAST_ERROR_CODE

 public static final String DEVICE_LAST_ERROR_CODE = "device_last_error_code";

请找到下面的代码。

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);

    }
}

在日志中得到这个看起来这个异常来自第 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.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

有问题的行是

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

这会解析一个整数,而不是一个浮点数;它需要一个整数的字符串表示。 5.3 不是整数且包含小数点,导致 NumberFormatException。使用 Float.parseFloatDouble.parseDouble 代替;根据您的用例,您可能希望将结果四舍五入为整数。

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.

啊...所以当你说“任何事情”时你没有任何意思?

可以通过三种方式来处理这个问题:

  1. 只需将错误代码作为字符串读取,不要尝试解析它。

    问问自己:您实际上需要将错误代码视为数字吗?那能给你带来什么?如果错误代码根本不是可识别的数字怎么办? (你的应用能应付吗?)

  2. 使用parseDouble解析错误代码,并将其表示为doubleparseDouble 解析的语法与 parseFloat 相同,并且是 parseInt 所接受内容的超集。具体来说,parseDouble 将愉快地解析一个整数值...并为您提供该整数的 double 表示。

    缺点是对于足够大的整数,double 表示将不精确/不准确。根据实际代码值,这可能会导致问题。

  3. 如果你必须用正确的类型解析它,那么你避免 try / catch 的方法是使用 Pattern 来实现正则表达式来测试错误代码是哪种预期格式中。然后调用对应的parseXXX方法进行解析。

    缺点是您现在需要三个(或更多)类型为 intfloatdouble 等的不同变量来表示已解析的错误代码值。并且您稍后在应用程序中使用错误代码的所有地方都必须处理该错误代码。

  4. 当然,您可以只使用序列 try-catches。