繁体   English   中英

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

[英]java.lang.NumberFormatException: For input string: "5.3"

运行此代码时,我收到此 java.lang.NumberFormatException:对于输入字符串:“5.3”异常。 我们如何解决这种类型的异常。任何其他方式我们可以在不尝试和捕获的情况下处理这个问题? 值可以是任何东西。它始终是浮点数并不是固定的。它也可以是整数和双精度数。有什么方法可以处理所有这三个,无论发生什么。不使用 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$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

有问题的行是

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

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

任何其他方式我们可以在不尝试捕获的情况下处理这个问题?

您需要使用正确的解析方法对其进行解析,以免引发异常。

价值可以是任何东西。

好吧,如果这确实是真的,则意味着您无法解析它,除非是最琐碎的意义。

它始终是浮点数并不固定。它也可以是整数和双精度数。

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

有三种可能的方法来处理这个问题:

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

    问问自己:您真的需要将错误代码视为数字吗? 那给你买什么? 如果错误代码根本不是一个可识别的数字怎么办? (您的应用程序能够应付吗?)

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

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

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

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

  4. 当然,您可以只使用序列尝试捕获。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM