はじめに
Java のIntegerクラスのdecode()メソッドは、文字列を整数値にデコードするために使用されます。このメソッドは、10 進数、16 進数、または 8 進数の文字列をデコードでき、文字列が保持するIntegerオブジェクトの整数値を返します。この実験では、いくつかの例を使ってdecode()メソッドの使い方を学びます。
Java のIntegerクラスのdecode()メソッドは、文字列を整数値にデコードするために使用されます。このメソッドは、10 進数、16 進数、または 8 進数の文字列をデコードでき、文字列が保持するIntegerオブジェクトの整数値を返します。この実験では、いくつかの例を使ってdecode()メソッドの使い方を学びます。
decode()メソッドの構文は次のとおりです。
public static Integer decode(String s) throws NumberFormatException
ここで:
sはデコードする文字列です。NumberFormatExceptionがスローされます。mainメソッドに次のコードを追加します。
String s = "100";
Integer decoded = Integer.decode(s);
System.out.println("Decimal decoded value is:" + decoded);
コマンドを使用してコードを保存して実行します。
javac Main.java && java Main
次の出力が得られます。
Enter the string to be decoded:
100
Decoded value is:100
これにより、文字列"100"を 10 進数としてデコードし、デコードされた値を100として表示します。
mainメソッドに次のコードを追加します。
String s = "017";
Integer decoded = Integer.decode(s);
System.out.println("Octal decoded value is:" + decoded);
コマンドを使用してコードを保存して実行します。
javac Main.java && java Main
次の出力が得られます。
Enter the string to be decoded:
017
Decoded value is:15
これにより、文字列"017"を 8 進数としてデコードし、デコードされた値を15として表示します。
mainメソッドに次のコードを追加します。
String s = "0x18";
Integer decoded = Integer.decode(s);
System.out.println("Hexadecimal decoded value is:" + decoded);
コマンドを使用してコードを保存して実行します。
javac Main.java && java Main
次の出力が得られます。
Enter the string to be decoded:
0x18
Decoded value is:24
これにより、文字列"0x18"を 16 進数としてデコードし、デコードされた値を24として表示します。
mainメソッドに次のコードを追加します。
String s = "-0x30";
Integer decoded = Integer.decode(s);
System.out.println("Signed hexadecimal decoded value is:" + decoded);
コマンドを使用してコードを保存して実行します。
javac Main.java && java Main
次の出力が得られます。
Enter the string to be decoded:
-0x30
Decoded value is:-48
これにより、文字列"-0x30"を符号付き 16 進数としてデコードし、デコードされた値を-48として表示します。
mainメソッドに次のコードを追加します。
String s = "abc";
try {
Integer decoded = Integer.decode(s);
System.out.println("Decoded value is:" + decoded);
} catch (NumberFormatException e) {
System.out.println("Invalid String: " + s);
}
コマンドを使用してコードを保存して実行します。
javac Main.java && java Main
次の出力が得られます。
Enter the string to be decoded:
abc
Invalid String: abc
これにより、無効な文字列をデコードする際に発生する可能性のある NumberFormatException を処理します。
この実験では、Java の Integer クラスの decode() メソッドの構文、パラメータ、戻り値、および使用方法について学びました。また、10 進数、8 進数、および 16 進数の文字列をデコードすることで、decode() メソッドの実際の操作に触れることができました。また、NumberFormatException を処理する方法も学びました。これで、有効な文字列をデコードしてそこから Integer 値を取得するために decode() メソッドを使用できるようになりました。