ホームページ  >  記事  >  Java  >  JavaのNumberFormatException

JavaのNumberFormatException

WBOY
WBOYオリジナル
2024-08-30 16:14:14657ブラウズ

NumberFormatException は、ユーザーが文字列を数値に変換しようとしたときに発生する Java の未チェック例外です。 NumberFormatException は、Java.lang.NumberFormatException パッケージで定義されている Java の組み込みクラスです。 IllegalArgumentException クラスは、未チェック例外である NumberFormatException のスーパークラスであるため、強制的に処理して宣言する必要はありません。 NumberFormatException は、実際には、入力文字列の形式が不正で適切ではないため、関数が文字列を integer、float、double などの数値に変換またはフォーマット (変換) できない場合に、parseXXX() 関数によってスローされます。 。たとえば、Java プログラムでは、コマンドライン引数を介して文字列形式のテキスト フィールドとしてユーザー入力が受け入れられることがあります。この文字列を算術演算で使用するには、まずラッパー クラスの parseXXX() 関数を使用して解析するか、データ型 (特定の数値型) に変換する必要があります。

無料ソフトウェア開発コースを始めましょう

Web 開発、プログラミング言語、ソフトウェア テスト、その他

NumberFormatException クラスの階層は次のとおりです:

オブジェクト ->スロー可能 -> 例外 ->RuntimeException ->NumberFormatException.

構文

以下は java.io の宣言です。 PrintWriter クラス。

public class NumberFormatException extends IllegalArgumentException implements Serializable
{
// Constructors of the NumberFormatException class
}

上記は NumberFormatException の構文であり、次のように拡張されています。

IllegalArgumentException class and implements Serializable

Java で NumberFormatException はどのように動作しますか?

文字列を数値に変換しようとすると、NumberFormatException が発生します。この種の変換は、Integer.parseInt()、Float.parseFloat() などの関数を使用して実行されます。 Integer.parseInt(s) 関数を呼び出すとします。ここで、s は String 型で、その値は文字列「30」であるため、この関数は文字列値を int 30 に正しく変換します。しかし、何が起こったでしょうか。 s の値が「30」であると想定されている場合、これは不正であり、関数は失敗し、例外 NumberFormatException をスローします。この例外を処理するには、その例外の catch ブロックを作成します。例外が処理されない場合、プログラムはクラッシュします。

以下に示すように、NumberFormatException がスローされるにはさまざまな理由があります –

  • 変換対象として指定された文字列が null である可能性があります。例:Integer.parseInt(null);
  • 指定された文字列の長さはゼロである可能性があります。例 :Integer.parseInt(“”);
  • 指定された文字列には数字が含まれていない可能性があります。例:Integer.parseInt(“30”);
  • 指定された文字列は整数値を表していない可能性があります。例 :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

次に、NumberFormatException をより明確に理解するための Java コードを作成します。次の例では、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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。