Java 中的 NumberFormatException
NumberFormatException 是 java 中的未经检查的异常,当用户尝试将字符串转换为数值时发生。 NumberFormatException 是 java 中的内置类,定义在 Java.lang.NumberFormatException 包中。 IllegalArgumentException 类是 NumberFormatException 的超类,因为它是未经检查的异常,因此不强制处理和声明它。 NumberFormatException 实际上是由 parseXXX() 函数抛出的,当函数无法将字符串转换或格式化(convert)为整数、浮点、双精度等数字值时,因为输入字符串的格式非法且不合适。例如,在 Java 程序中,有时用户输入通过命令行参数作为字符串形式的文本字段接受。并且要在某些算术运算中使用此字符串,应首先使用包装类的 parseXXX() 函数解析或转换为数据类型(特定数字类型)。
开始您的免费软件开发课程
网络开发、编程语言、软件测试及其他
NumberFormatException 类的层次结构是:
对象 ->可抛出 -> 异常 ->RuntimeException ->NumberFormatException。
语法
以下是java.io的声明。 PrintWriter 类。
public class NumberFormatException extends IllegalArgumentException implements Serializable { // Constructors of the NumberFormatException class }
上面是NumberFormatException的语法,在这里它被扩展为:
IllegalArgumentException class and implements Serializable
NumberFormatException 在 Java 中如何工作?
当尝试将字符串转换为数字时,会发生 NumberFormatException。这种类型的转换是通过使用 Integer.parseInt()、Float.parseFloat() 等函数来执行的。假设我们调用 Integer.parseInt(s) 函数,其中 s 是 String 类型,其值为字符串“30”,因此该函数将字符串值正确转换为 int 30。但是发生了什么?如果 s 的值被假定为“三十”(这是非法的),则该函数将失败并引发异常:NumberFormatException。为了处理这个异常,我们可以为其编写catch块;如果不处理异常,程序就会崩溃。
抛出 NumberFormatException 的原因有多种,如下所示 –
- 提供的要转换的字符串可能为空。例如:Integer.parseInt(null);
- 提供的字符串长度可能为零。例如:Integer.parseInt(“”);
- 提供的字符串可能没有数字字符。例如:Integer.parseInt(“三十”);
- 提供的字符串可能不代表整数值。例如:Integer.parseInt(“FG67”);
- T 提供的字符串可能为空。例如:Integer.parseInt(“”);
- 提供的字符串可能尾随空格。例如:Integer.parseInt(“785”);
- 提供的字符串可能有前导空格。例如:Integer.parseInt(“785”);
- 提供的字符串可能包含字母数字。例如:Long.parseLong(“F5”);
- 提供的字符串可能是支持的数据类型超出范围。例如:Integer.parseInt(“139”);
- 提供的字符串和用于转换的函数可能是不同的数据类型。Ex :Integer.parseInt(“3.56”);
构造函数
- NumberFormatException(): 此构造函数创建 NumberFormatException,但没有详细的特定消息。
- NumberFormatException(String s): 此构造函数创建包含特定消息详细信息的 NumberFormatException。
在 Java 中实现 NumberFormatException 的示例
以下是实施示例:
示例#1
接下来,我们编写java代码来更清楚地理解NumberFormatException,通过以下示例,我们使用PrintWriter类构造函数创建一个PrintWriter对象,并传递要写入的文件名,如下所示 –
代码:
//package p1; import java.util.Scanner; public class Demo { public static void main( String[] arg) { int age; Scanner sc = new Scanner(System.in); System.out.println("Please Enter your age : "); //throws Exception as if the input string is of illegal format for parsing as it as null or alphanumeric. age = Integer.parseInt(sc.next()); System.out.println("Your age is : " +age); } }
输出:
当用户输入“25+”时,上述代码的输出为:
当用户输入格式不正确的字符串“25F”时,输出为:
当用户输入字符串“Twenty Five”时,输出为:
当用户输入字符串“null”时,输出为:
当用户输入浮点型“40.78”字符串值时,输出为:
When the user enters a string “25”, which is a valid string. The output is:
Explanation: As in the above code, the age value is accepted from the user in string format, which further converts into the integer format by using the Integer.parseInt(sc.next()) function. While the user an illegal input string or not a well-formatted string, the NumberFormatException occurs, it throws, and the program terminates unsuccessfully. So to provide the valid string, it should be taken care that an input string should not be null, check an argument string matches the type of the conversion function used and also check if any unnecessary spaces are available; if yes, then trim it and so all care must be taken.
Example #2
Next, we write the java code to understand the NumberFormatException where we generate the NumberFormatException and handle it by using the try-catch block in the program, as below –
Code:
//package p1; import java.util.Scanner; public class Demo { public static void main( String[] arg) { int age; Scanner sc = new Scanner(System.in); try { System.out.println("Please Enter your age : "); //throws Exception as if the input string is of illegal format for parsing as it as null or alphanumeric. age = Integer.parseInt(sc.next()); System.out.println("Your age is : " +age); } catch(NumberFormatException e) { System.out.println("The NumberFormatExceptionoccure."); System.out.println("Please enter the valid age."); } } }
When the user enters a string “23F”, the output is:
When a user enters a string “23”, the output is:
Explanation: As in the above code try-catch block is used. It is always a good practice to enclose lines of code that can throw an exception in a try-catch block by which it handles the NumberFormatException and prevents it from generating the Exception.
Conclusion
The NumberFormatException in java is an unchecked exception that occurs when a not well-formatted string is trying to converts into a numeric value by using the parseXXX() functions. The NumberFormatException is a built-in class in which is defined in the Java.lang.NumberFormatException package.
以上是Java 中的 NumberFormatException的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

AI可以帮助优化Composer的使用,具体方法包括:1.依赖管理优化:AI分析依赖关系,建议最佳版本组合,减少冲突。2.自动化代码生成:AI生成符合最佳实践的composer.json文件。3.代码质量提升:AI检测潜在问题,提供优化建议,提高代码质量。这些方法通过机器学习和自然语言处理技术实现,帮助开发者提高效率和代码质量。

MySQL函数可用于数据处理和计算。1.基本用法包括字符串处理、日期计算和数学运算。2.高级用法涉及结合多个函数实现复杂操作。3.性能优化需避免在WHERE子句中使用函数,并使用GROUPBY和临时表。

HTML5带来了五个关键改进:1.语义化标签提升了代码清晰度和SEO效果;2.多媒体支持简化了视频和音频嵌入;3.表单增强简化了验证;4.离线与本地存储提高了用户体验;5.画布与图形功能增强了网页的可视化效果。

typetraits在C 中用于编译时类型检查和操作,提升代码的灵活性和类型安全性。1)通过std::is_integral和std::is_floating_point等进行类型判断,实现高效的类型检查和输出。2)使用std::is_trivially_copyable优化vector拷贝,根据类型选择不同的拷贝策略。3)注意编译时决策、类型安全、性能优化和代码复杂性,合理使用typetraits可以大大提升代码质量。

在MySQL中配置字符集和排序规则的方法包括:1.设置服务器级别的字符集和排序规则:SETNAMES'utf8';SETCHARACTERSETutf8;SETCOLLATION_CONNECTION='utf8_general_ci';2.创建使用特定字符集和排序规则的数据库:CREATEDATABASEexample_dbCHARACTERSETutf8COLLATEutf8_general_ci;3.创建表时指定字符集和排序规则:CREATETABLEexample_table(idINT

MySQL中重命名数据库需要通过间接方法实现。步骤如下:1.创建新数据库;2.使用mysqldump导出旧数据库;3.将数据导入新数据库;4.删除旧数据库。

在C 中实现单例模式可以通过静态成员变量和静态成员函数来确保类只有一个实例。具体步骤包括:1.使用私有构造函数和删除拷贝构造函数及赋值操作符,防止外部直接实例化。2.通过静态方法getInstance提供全局访问点,确保只创建一个实例。3.为了线程安全,可以使用双重检查锁定模式。4.使用智能指针如std::shared_ptr来避免内存泄漏。5.对于高性能需求,可以使用静态局部变量实现。需要注意的是,单例模式可能导致全局状态的滥用,建议谨慎使用并考虑替代方案。

Java代码可以在不同操作系统上无需修改即可运行,这是因为Java的“一次编写,到处运行”哲学,由Java虚拟机(JVM)实现。JVM作为编译后的Java字节码与操作系统之间的中介,将字节码翻译成特定机器指令,确保程序在任何安装了JVM的平台上都能独立运行。
