首頁  >  文章  >  Java  >  Java 中的 NumberFormatException

Java 中的 NumberFormatException

WBOY
WBOY原創
2024-08-30 16:14:14657瀏覽

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+」時,上述程式碼的輸出為:

Java 中的 NumberFormatException

當使用者輸入格式不正確的字串「25F」時,輸出為:

Java 中的 NumberFormatException

當使用者輸入字串「Twenty Five」時,輸出為:

Java 中的 NumberFormatException

當使用者輸入字串「null」時,輸出為:

Java 中的 NumberFormatException

當使用者輸入浮點型「40.78」字串值時,輸出為:

Java 中的 NumberFormatException

When the user enters a string “25”, which is a valid string. The output is:

Java 中的 NumberFormatException

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:

Java 中的 NumberFormatException

When a user enters a string “23”, the output is:

Java 中的 NumberFormatException

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn