📜  Java中的 NumberFormatException 示例

📅  最后修改于: 2022-05-13 01:55:29.815000             🧑  作者: Mango

Java中的 NumberFormatException 示例

当尝试将格式不正确的字符串转换为数值时,会发生 NumberFormatException。这意味着,当无法转换任何数字类型(float、int 等)的字符串时,将抛出此异常。它是Java中的运行时异常(Unchecked Exception)。它是 IllegalArgumentException 类的子类。要处理此异常,可以使用 try-catch 块。

在对字符串进行操作时,有时我们需要将表示为字符串的数字转换为整数类型。 Java中通常用于将String转换为Integer的方法是parseInt()。

parseInt()方法的用法:我们已经知道这个方法有两种变体,如下所示,以便更好地理解

public static int parseInt(String s) throws NumberFormatException

This function parses the string argument as a signed decimal integer.
public static int parseInt(String s, int radix) throws NumberFormatException

This function parses the string argument as a signed integer in the radix specified by the second argument.

退货类型:

简而言之,这两种方法都将字符串转换为其等效的整数。唯一的区别是参数基数的区别。第一种方法可以看作是 radix = 10(十进制)的第二种方法的等效方法。

构造函数:

  1. public NumberFormatException():构造一个没有详细消息的 NumberFormatException。
  2. public NumberFormatException(String msg):构造一个带有详细消息“msg”的 NumberFormatException

NumberFormatException 的常见原因:

有各种与数值转换的字符串格式不正确有关的问题。其中一些是:

1.输入字符串为空

Integer.parseInt("null") ;

2.输入字符串为空

Float.parseFloat(“”) ; 

3.带有前导和/或尾随空格的输入字符串

Integer abc=new Integer(“  432 “);

4.带有额外符号的输入字符串

Float.parseFloat(4,236);

5.非数字数据的输入字符串

Double.parseDouble(“ThirtyFour”);

6.输入字符串是字母数字

Integer.valueOf(“31.two”);

7.输入字符串可能超出存储解析字符串的数据类型范围

Integer.parseInt(“1326589741236”); 

8.输入字符串值与解析方法的类型不匹配

Integer.parseInt("13.26");

例子:

Java
// Java Program to illustrate NumberFormatException
 
// Importing Scanner class to take
// input number from the user
import java.util.Scanner;
 
//  Class
public class GFG {
 
    // Main driver method
    public static void main(String[] arg)
    {
        // Declaring an variable which
        // holds the input number entered
        int number;
 
        // Creating a Scanner class object to
        // take input from keyboard
        // System.in -> Keyboard
        Scanner sc = new Scanner(System.in);
 
        // Condition check
        // If condition holds true, Continue loop until
        // valid integer is entered by user
        while (true) {
 
            // Display message
            System.out.println("Enter any valid Integer: ");
 
            // Try block to check if any exception occurs
            try {
 
                // Parsing user input to integer
                // using the parseInt() method
                number = Integer.parseInt(sc.next());
 
                // Number can be valid or invalid
 
                // If number is valid, print and display
                // the message and number
                System.out.println("You entered: "
                                   + number);
 
                // Get off from this loop
                break;
            }
 
            // Catch block to handle NumberFormatException
            catch (NumberFormatException e) {
 
                // Print the message if exception occured
                System.out.println(
                    "NumberFormatException occured");
            }
        }
    }
}



输出:以下输出是针对用户输入的不同数字

Enter any valid Integer:
12,017
NumberFormatException occurred
Enter any valid Integer:
Sixty4
NumberFormatException occurred
Enter any valid Integer:
null
NumberFormatException occurred
Enter any valid Integer:
436.25
NumberFormatException occurred
Enter any valid Integer:
3.o
NumberFormatException occurred
Enter any valid Integer:
98562341789
NumberFormatException occurred
Enter any valid Integer:
1000
You entered: 1000