Home Common Problem What is numberformatexception?

What is numberformatexception?

Jan 14, 2021 pm 06:25 PM
numberformatexception abnormal

numberformatexception indicates a number formatting exception. You need to check whether the string is mixed with string or other types. It is important to note that the content in the text must be a string in the form of a number.

What is numberformatexception?

The operating environment of this tutorial: Windows 7 system, Dell G3 computer.

A digital conversion exception occurred today. After handling it, I briefly summarized several scenarios.




#E/AdroidRutime: Fatal exception: java.lang.NumberFormatException: Invalid int: "0 "

##java.lang .NumberFormatExceptionNumber format exception. This exception is thrown when trying to convert a String to a specified numeric type, but the string does not meet the format required by the numeric type.

Invalid int: "0 " Tips Convert "0 " An error occurred when converting it into a numeric type.

Specifically, the error occurred in which method of which class and which line. Please see the error stack below, at com. example.myclock.TimerView$5.onTextChanged(TimerView.java:95) In the onTextChanged method of the com.example.myclock.TimerView class, An error occurred on line 95 of imerView.java##.

---- --Cause Analysis--------------------

"0 "There is a space after 0, and the space should be removed when the string is converted into a number.

------solution--------------------

For example: int vale=Integer .parseInt(s.toString() .trim()); // ToString() is converted into a string The method Trim() is a method to remove spaces on both sides of a string.

Other throwing NumberFormatException situations:

Case 1 , beyond the conversion range of numerical types:

Thrown when using Integer.parseInt() to convert charactersNumberFormatExceptionException, change the characters to a shorter length and it will be fine
##String line3[1]= "8613719716 ";
int int1=java.lang.Integer.parseInt(line3[1]);

The above is a short section of the program, but when running Exceptions are always thrown during the process
Exception in thread "main " java.lang.NumberFormatException: For input string: "8613719716 "

------Cause Analysis-------------- ------

The storage range of int type is -2,147,483,648 --2,147,483,647. Use System.out.println(Integer.MAX_VALUE); the output is 2147483647. And your String line3[1]= "8613719716 "; exceeds this maximum value.

------solution--------------------

8613719716 It cannot be directly represented by int, you can only use long, If it is larger, you have to use BigInteger. Long.parseLong(String).

Reference: http://www.myexception.cn/j2se/NumberFormatException.html

Case 2, The conversion value type does not consider the situation of the value being empty:

Is this sequence correct in Android? I plan to put the obtained edittext Convert the value to an integer .

##startTime_hour_int=Integer.parseInt(startTime_hour_edittext.getEditableText().toString());

The following error occurred in logcat. 05-12 10:26:35.536: ERROR/AndroidRuntime(293): java.lang.NumberFormatException: unable to parse ' ' as integer

. ------Cause Analysis--------------------

If textbox startTime_hour_edittext is empty, Integer.parseInt will try to convert "" into integer. This is why NumberFormatException occurs. Therefore, you need to determine whether textbox startTime_hour_edittext is empty before converting to int type.

------solution--------------------

Before using <span >startTime_hour_int=Integer.parseInt(startTime_hour_edittext.getEditableText().toString());</span><span style="font-family:Arial,\Helvetica Neue\, Helvetica,sans-serif; color:#242729"></span>

Judgment conditions:

if(!startTime_hour_edittext.getText().toString().equalsIgnoreCase("")) {
startTime_hour_int=Integer.parseInt(startTime_hour_edittext.getEditableText().toString());
}
Copy after login

Case 3, due to different base systems:

The question mainly involves a base conversion. And The range is limited to 30-digit numbers (1073741823) or (0111111111111111111111111111111). The problem occurs when trying to convert 1111111111111111111111111111111. NumberFormatException.

This code checks if the input is binary and converts it to int. Type value

if (checkNumber(input)) {
        try {
        number = Integer.parseInt(input);
        } catch (NumberFormatException ex) {
            log(ex.getMessage());
        }
    } else {
        toDecimal();
    }
Copy after login

This is the code for checking the Boolean return value method of String.

private static boolean checkNumber(String input) {
    for (char c : input.toCharArray()) {
        if (!Character.isDigit(c)) {
            return false;
        }
    }

    return true;}
Copy after login

Exception occurred:

java.lang.NumberFormatException: For input string: "111111111111111111111111111111"
Copy after login

------Cause Analysis------ ---------------

因为 Integer.parseInt(String) 默认是十进制.

所以需要使用 Integer.parseInt(String, int) 并且指定要转换的n进制的数字的n。比如二进制是2.

------解决方案--------------------

int value = Integer.parseInt(input, 2);
Copy after login

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of What is numberformatexception?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the common causes of OutOfMemoryError exceptions in Java? What are the common causes of OutOfMemoryError exceptions in Java? Jun 25, 2023 pm 08:43 PM

Java is one of the most widely used programming languages, but when developing applications using Java, it is easy to encounter "OutOfMemoryError" exception errors, which often bring some challenges to developers. What exactly causes the OutOfMemoryError exception in Java? Next, let’s take a closer look. Memory Leak (MemoryLeak) Memory leak refers to when an object cannot be recycled by the garbage collector, it will cause a memory leak.

How to solve Java thread interrupt timeout exception (ThreadInterruptedTimeoutExceotion) How to solve Java thread interrupt timeout exception (ThreadInterruptedTimeoutExceotion) Aug 18, 2023 pm 01:57 PM

How to solve the Java thread interrupt timeout exception (ThreadInterruptedTimeoutException). In Java multi-thread programming, we often encounter situations where the thread execution time is too long. In order to prevent threads from occupying too many system resources, we usually set a timeout. When the thread execution time exceeds the timeout, we hope to be able to interrupt the execution of the thread. Java provides a thread interruption mechanism. By calling the thread's interrupt() method, you can

Methods to solve Java reflection exception (ReflectiveOperationException) Methods to solve Java reflection exception (ReflectiveOperationException) Aug 26, 2023 am 09:55 AM

Methods to solve Java reflection exceptions (ReflectiveOperationException) In Java development, reflection (Reflection) is a powerful mechanism that allows programs to dynamically obtain and operate classes, objects, methods, properties, etc. at runtime. Through reflection, we can implement some flexible functions, such as dynamically creating objects, calling private methods, obtaining class annotations, etc. However, using reflection also brings some potential risks and problems, one of which is reflection anomalies (

A guide to the unusual missions in the Rise of Ronin Pool A guide to the unusual missions in the Rise of Ronin Pool Mar 26, 2024 pm 08:06 PM

The abnormality in the pool is a side task in the game. Many players want to know how to complete the abnormality in the pool task. It is actually very simple. First, we must master the technique of shooting in the water before we can accept the task and investigate the source of the stench. Later, we discovered It turns out that there are a lot of corpses under the pool. Let’s take a look at this graphic guide for the unusual tasks in the pool in Rise of Ronin. Guide to unusual missions in the Ronin Rise Pool: 1. Talk to Iizuka and learn the technique of shooting in the water. 2. Go to the location in the picture below to receive the abnormal task in the pool. 3. Go to the mission location and talk to the NPC, and learn that there is a foul smell in the nearby pool. 4. Go to the pool to investigate. 5. Swim to the location in the picture below, dive underwater, and you will find a lot of corpses. 6. Use a camera to take pictures of the corpse. 7

NumberFormatException exception solution NumberFormatException exception solution Jul 26, 2023 am 10:26 AM

NumberFormatException exception solution: 1. Use the try-catch statement to catch the exception. You can put the conversion function in the try block and handle the exception in the catch block; 2. You can use regular expressions to verify whether the string conforms to the format of the numerical type. Requirements, if the string does not meet the requirements, we can handle the error in advance; 3. Use the static method isDigit() to verify whether the character is a number. If there are non-numeric characters, we can handle the error in advance.

Practical tips for efficiently solving Java large file reading exceptions Practical tips for efficiently solving Java large file reading exceptions Feb 21, 2024 am 10:54 AM

Practical tips for efficiently resolving large file read exceptions in Java require specific code examples. Overview: When processing large files, Java may face problems such as memory overflow and performance degradation. This article will introduce several practical techniques to effectively solve Java large file reading exceptions, and provide specific code examples. Background: When processing large files, we may need to read the file contents into memory for processing, such as searching, analyzing, extracting and other operations. However, when the file is large, the following problems are often encountered: Memory overflow: trying to copy the entire file at once

MIT's latest masterpiece: using GPT-3.5 to solve the problem of time series anomaly detection MIT's latest masterpiece: using GPT-3.5 to solve the problem of time series anomaly detection Jun 08, 2024 pm 06:09 PM

Today I would like to introduce to you an article published by MIT last week, using GPT-3.5-turbo to solve the problem of time series anomaly detection, and initially verifying the effectiveness of LLM in time series anomaly detection. There is no finetune in the whole process, and GPT-3.5-turbo is used directly for anomaly detection. The core of this article is how to convert time series into input that can be recognized by GPT-3.5-turbo, and how to design prompts or pipelines to let LLM solve the anomaly detection task. Let me introduce this work to you in detail. Image paper title: Largelanguagemodelscanbezero-shotanomalydete

C++ function exceptions and single testing: ensuring code soundness C++ function exceptions and single testing: ensuring code soundness May 03, 2024 am 09:18 AM

Exception handling and unit testing are important practices to ensure the soundness of C++ code. Exceptions are handled through try-catch blocks, and when the code throws an exception, it jumps to the catch block. Unit testing isolates code testing to verify that exception handling works as expected under different circumstances. Practical case: The sumArray function calculates the sum of array elements and throws an exception to handle an empty input array. Unit testing verifies the expected behavior of a function under abnormal circumstances, such as throwing an std::invalid_argument exception when an array is empty. Conclusion: By leveraging exception handling and unit testing, we can handle exceptions, prevent code from crashing, and ensure that the code behaves as expected under abnormal conditions.