how convert java string int tutorial with examples
このチュートリアルでは、Integer.parseIntメソッドとInteger.ValueOfメソッドを使用してJava文字列を整数に変換する方法をコード例とともに説明します。
Java文字列をint値に変換するために使用される次の2つの整数クラス静的メソッドについて説明します。
- Integer.parseInt()
- Integer.valueOf()
=> ここですべてのJavaチュートリアルを確認してください
学習内容:
Java文字列からIntへの変換
数値に対してある種の算術演算を実行する必要があるシナリオを考えてみましょう。ただし、この数値は文字列の形式で利用できます。番号が、WebページのテキストフィールドまたはWebページのテキスト領域からのテキストとして取得されているとします。
このようなシナリオでは、最初にこの文字列を変換して、整数形式の数値を取得する必要があります。
例えば、 2つの数字を追加したいシナリオを考えてみましょう。これらの値は、「300」および「200」としてWebページからテキストとして取得され、これらの数値に対して算術演算を実行します。
サンプルコードを使用してこれを理解しましょう。ここでは、「300」と「200」の2つの数値を追加し、それらを変数「c」に割り当てようとしています。 「c」を出力すると、コンソールでの出力は「500」になると予想されます。
package com.softwaretestinghelp; public class StringIntDemo{ public static void main(String() args) { //Assign text '300' to String variable String a='300'; //Assign text '200' to String variable String b='200'; //Add variable value a and b and assign to c String c=a+b; //print variable c System.out.println('Variable c Value --->'+c);//Expected output as 500 } } Here is the program Output : Variable c Value --->300200
しかし、上記のプログラムでは、コンソールに出力される実際の出力は
「変数c値—> 300200」 。
この出力を印刷する理由は何でしょうか?
これに対する答えは、a + bを実行したとき、連結として「+」演算子を使用しているということです。だから、 c = a + b; Javaは文字列aとbを連結しています。つまり、2つの文字列「300」と「200」を連結して印刷しています。 「300200」。
したがって、これは2つの文字列を追加しようとしたときに発生します。
では、これら2つの数値を加算する場合は、どうすればよいでしょうか。
このためには、最初にこれらの文字列を数値に変換してから、これらの数値に対して算術演算を実行する必要があります。 Java Stringをintに変換するために、JavaIntegerクラスによって提供される次のメソッドを使用できます。
- Integer.parseInt()
- Integer.valueOf()
これらの方法を1つずつ詳しく見ていきましょう。
#1)Java Integer.parseInt()メソッドの使用
parseInt()メソッドは、クラスIntegerクラスによって提供されます。 Integerクラスは、プリミティブ型intの値をオブジェクトにラップするため、Wrapperクラスと呼ばれます。
以下のメソッドシグネチャを見てみましょう。
public static int parseInt(String str)はNumberFormatExceptionをスローします
public static Integer valueOf(String str)throws NumberFormatException
これは、渡されたStringオブジェクトによって指定された値を持つ整数クラスのオブジェクトを返すIntegerクラスによって提供される静的メソッドです。ここでは、渡された引数の解釈は符号付き10進整数として行われます。
これは、parseInt(java.lang.String)メソッドに渡される引数と同じです。返される結果は、Stringで指定された整数値を表すIntegerクラスオブジェクトです。簡単に言うと、valueOf()メソッドはの値に等しい整数オブジェクトを返します。
new Integer(Integer.parseInt(str))
ここで、「str」パラメータは整数表現を含む文字列であり、メソッドはメソッド内の「str」で表される値を保持するIntegerオブジェクトを返します。
このメソッドは例外をスローします NumberFormatException 文字列に解析可能な整数が含まれていない場合。
符号のない文字列のInteger.parseInt()メソッド
前のサンプルで見たのと同じJavaプログラムでこのInteger.parseInt()メソッドを使用する方法を理解してみましょう。
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert String to int Java program * using Integer.parseInt() method using String having decimal digits without * ASCII sign i.e. plus + or minus - * */ public class StringIntDemo { public static void main(String() args) { //Assign text '300' to String variable a String a='300'; //Pass a i.e.String “300” as a parameter to parseInt() //to convert String 'a' value to integer //and assign it to int variable x int x=Integer.parseInt(a); System.out.println('Variable x value --->'+x); //Assign text '200' to String variable b String b='200'; //Pass b i.e.String “200” as a parameter to parseInt() //to convert String 'b' value to integer //and assign it to int variable y int y=Integer.parseInt(b); System.out.println('Variable y value --->'+y); //Add integer values x and y i.e.z = 300+200 int z=x + y; //convert z to String just by using '+' operator and appending '' String c=z + ''; //Print String value of c System.out.println('Variable c value --->'+c); } }
プログラムの出力は次のとおりです。
変数x値—> 300
変数と値-> 200
変数c値—> 500
したがって、これで、目的の出力、つまりテキストとして表される2つの数値の合計を、それらをint値に変換し、これらの数値に対して追加の操作を実行することで取得できます。
符号付き文字列のInteger.parseInt()メソッド
上記のInteger.parseInt()メソッドの説明に示されているように、最初の文字は、負の値を示す場合はASCIIマイナス記号「-」、正の値を示す場合はASCIIプラス記号「+」にすることができます。値。同じプログラムを負の値で試してみましょう。
「+」や「-」などの値と記号を使用したサンプルプログラムを見てみましょう。
「+75」や「-75000」などの符号付き文字列値を使用し、それらを整数に解析してから比較して、これら2つの数値の間のより大きな数値を見つけます。
package com.softwaretestinghelp; /** * This class demonstrates sample code to convert string to int Java * program using Integer.parseInt() method * on string having decimal digits with ASCII signs i.e. plus + or minus - * @author * */ public class StringIntDemo1 { public static void main(String() args) { //Assign text '75' i.e.value with ‘+’ sign to string variable a String a='+75'; //Pass a i.e.String “+75” as a parameter to parseInt() //to convert string 'a' value to integer //and assign it to int variable x int x =Integer.parseInt(a); System.out.println('Variable x value --->'+x); //Assign text '-75000' i.e.value with ‘-’ sign to string variable b String b='-75000'; //Pass b i.e.String “-75000” as a parameter to parseInt() //to convert string 'b' value to integer //and assign it to int variable y int y = Integer.parseInt(b); System.out.println('Variable y value --->'+y); //Get higher value between int x and y using Math class method max() int maxValue = Math.max(x,y); //convert maxValue to string just by using '+' operator and appending '' String c = maxValue + ''; //Print string value of c System.out.println('Larger number is --->'+c); }
プログラムの出力は次のとおりです。
変数x値—> 75
変数と値->-75000
大きい数は—> 75
先行ゼロのある文字列のInteger.parseInt()メソッド
場合によっては、先行ゼロのある数値に対しても算術演算を行う必要があります。 Integer.parseInt()メソッドを使用して、先行ゼロの数値を持つ文字列をint値に変換する方法を見てみましょう。
例えば、 一部の金融ドメインソフトウェアシステムでは、アカウント番号または金額に先行ゼロを付けるのが標準形式です。同様に、次のサンプルプログラムでは、金利と定期預金額を使用して定期預金額の満期額を計算しています。
ここで、金額は先行ゼロを使用して指定されます。先行ゼロを含むこれらの文字列値は、Integerを使用して整数値に解析されます。
以下のプログラムに見られるparseInt()メソッド:
package com.softwaretestinghelp; /** * This class demonstrates sample program to convert string with leading zeros to int java * using Integer.parseInt() method * * @author * */ public class StringIntDemo2{ public static void main(String() args) { //Assign text '00010000' i.e.value with leading zeros to string variable savingsAmount String fixedDepositAmount='00010000'; //Pass 0010000 i.e.String “0010000” as a parameter to parseInt() //to convert string '0010000' value to integer //and assign it to int variable x int fixedDepositAmountValue = Integer.parseInt(fixedDepositAmount); System.out.println('You have Fixed Deposit amount --->'+ fixedDepositAmountValue+' INR'); //Assign text '6' to string variable interestRate String interestRate = '6'; //Pass interestRate i.e.String “6” as a parameter to parseInt() //to convert string 'interestRate' value to integer //and assign it to int variable interestRateVaue int interestRateValue = Integer.parseInt(interestRate); System.out.println('You have Fixed Deposit Interst Rate --->' + interestRateValue+'% INR'); //Calculate Interest Earned in 1 year tenure int interestEarned = fixedDepositAmountValue*interestRateValue*1)/100; //Calcualte Maturity Amount of Fixed Deposit after 1 year int maturityAmountValue = fixedDepositAmountValue + interestEarned; //convert maturityAmount to string using format()method. //Use %08 format specifier to have 8 digits in the number to ensure the leading zeroes String maturityAmount = String.format('%08d', maturityAmountValue); //Print string value of maturityAmount System.out.println('Your Fixed Deposit Amount on maturity is --->'+ maturityAmount+ ' INR'); } }
プログラムの出力は次のとおりです。
定期預金の金額があります—> 10000 INR
定期預金金利—> 6%INR
満期時の定期預金額は—> 00010600 INR
したがって、上記のサンプルプログラムでは、「00010000」をparseInt()メソッドに渡して、値を出力しています。
String fixedDepositAmount='00010000'; int fixedDepositAmountValue = Integer. parseInt (fixedDepositAmount); System. out .println('You have Fixed Deposit amount --->'+ fixedDepositAmountValue+' INR');
定期預金の金額が10000インドルピーであるため、コンソールに値が表示されます。
ここでは、整数値に変換する際に、先行ゼロが削除されます。
次に、定期預金の満期額を「10600」整数値として計算し、%08フォーマット指定子を使用して結果値をフォーマットして先行ゼロを取得しました。
String maturityAmount = String. format ('%08d', maturityAmountValue);
フォーマットされた文字列の値を出力すると、
System. out .println('Your Fixed Deposit Amount on maturity is --->'+ maturityAmount+ ' INR');
出力がコンソールに印刷されるのを見ることができます 満期時の定期預金額は—> 00010600 INR
NumberFormatException
の説明で Integer.parseInt() メソッドでは、parseInt()メソッドによってスローされる例外も確認されています。 NumberFormatException。
このメソッドは例外をスローします。 NumberFormatException 文字列に解析可能な整数が含まれていない場合。
それでは、この例外がスローされるシナリオを見てみましょう。
このシナリオを理解するために、次のサンプルプログラムを見てみましょう。このプログラムは、スコアリングされたパーセンテージを入力するようにユーザーに促し、受け取った成績を返します。このために、ユーザーが入力した文字列値を整数値に解析します。
Package com.softwaretestinghelp; import java.util.Scanner; /** * This class demonstrates sample code to convert string to int Java * program using Integer.parseInt() method having string with non decimal digit and method throwing NumberFormatException * @author * */ public class StringIntDemo3{ private static Scanner scanner; public static void main(String() args){ //Prompt user to enter input using Scanner and here System.in is a standard input stream scanner = new Scanner(System.in); System.out.print('Please Enter the percentage you have scored:'); //Scan the next token of the user input as an int and assign it to variable precentage String percentage = scanner.next(); //Pass percentage String as a parameter to parseInt() //to convert string 'percentage' value to integer //and assign it to int variable precentageValue int percentageValue = Integer.parseInt(percentage); System.out.println('Percentage Value is --->' + percentageValue); //if-else loop to print the grade if (percentageValue>=75) { System.out.println('You have Passed with Distinction'); }else if(percentageValue>60) { System.out.println('You have Passed with Grade A'); }else if(percentageValue>50) { System.out.println('You have Passed with Grade B'); }else if(percentageValue>35) { System.out.println('You have Passed '); }else { System.out.println('Please try again '); } } }
プログラムの出力は次のとおりです。
ユーザーが入力した2つの異なる入力値を試してみましょう。
1.有効な整数値を使用
得点したパーセンテージを入力してください:82
パーセンテージ値は—> 82
あなたは区別して合格しました
2.InValid整数値を使用
得点したパーセンテージを入力してください:85a
スレッド「main」の例外java.lang.NumberFormatException:入力文字列の場合:「85a」
java.lang.NumberFormatException.forInputString(不明なソース)で
java.lang.Integer.parseInt(不明なソース)で
java.lang.Integer.parseInt(不明なソース)で
com.softwaretestinghelp.StringIntDemo3.main(StringIntDemo3.java:26)で
したがって、プログラム出力に見られるように、
#1)ユーザーが有効な値(入力として82)を入力すると、コンソールに表示される出力は次のようになります。
パーセンテージ値は—> 82
あなたは区別して合格しました
#2)ユーザーが無効な値(入力として85a)を入力すると、コンソールに表示される出力は次のようになります。
得点したパーセンテージを入力してください:85a
スレッド「main」の例外java.lang.NumberFormatException:入力文字列の場合:「85a」
java.lang.NumberFormatException.forInputString(不明なソース)で
java.lang.Integer.parseInt(不明なソース)で
java.lang.Integer.parseInt(不明なソース)で
com.softwaretestinghelp.StringIntDemo3.main(StringIntDemo3.java:26)で
Integer.parseInt()メソッドで85aを解析しているときにjava.lang.NumberFormatExceptionがスローされます。これは、「85a」の文字が「a」であり、10進数でもASCII記号でもない「+」または「-」であるためです。つまり、「85a」は解析可能ではありません。 Integer.parseInt()メソッドの整数。
つまり、これはJavaStringをintに変換する方法の1つでした。 JavaがStringをintに変換する別の方法、つまりInteger.valueOf()メソッドを使用する方法を見てみましょう。
Windows10用の最高のYouTubeダウンローダー
#2)整数を使用する。 valueOf()メソッド
valueOf()メソッドも整数クラスの静的メソッドです。
以下のメソッドシグネチャを見てみましょう。
public static int parseInt(String str)はNumberFormatExceptionをスローします
これは、渡されたStringオブジェクトによって指定された値を持つclassIntegerのオブジェクトを返すIntegerクラスによって提供される静的メソッドです。ここでは、渡された引数の解釈は符号付き10進整数として行われます。
これは、parseInt(java.lang.String)メソッドに渡される引数と同じです。返される結果は、Stringで指定された整数値を表すIntegerクラスオブジェクトです。簡単に言うと、valueOf()メソッドはの値に等しい整数オブジェクトを返します。 新着 Integer(Integer.parseInt(str))
ここで、「str」パラメータは整数表現を含む文字列であり、メソッドはメソッド内の「str」で表される値を保持するIntegerオブジェクトを返します。このメソッドは例外をスローします NumberFormatException 文字列に解析可能な整数が含まれていない場合。
このInteger.valueOf()メソッドの使用方法を理解しましょう。
以下にサンプルプログラムを示します。このサンプルコードは、週の3日間の平均気温を計算します。ここで、温度を変換するために、値は文字列値として整数値に割り当てられます。この文字列から整数への変換では、Integer.valueOf()メソッドを使用してみましょう。
Package com.softwaretestinghelp; /** * This class demonstrates a sample program to convert string to integer in Java * using Integer.valueOf() method * on string having decimal digits with ASCII signs i.e.plus + or minus - * @author * */ public class StringIntDemo4 { public static void main(String() args) { //Assign text '-2' i.e.value with ‘-’ sign to string variable sundayTemperature String sundayTemperature= '-2'; //Pass sundayTemperature i.e.String “-2” as a parameter to valueOf() //to convert string 'sundayTemperature' value to integer //and assign it to Integer variable sundayTemperatureValue Integer sundayTemperatureValue = Integer.valueOf(sundayTemperature); System.out.println('Sunday Temperature value --->'+ sundayTemperatureValue); //Assign text '4' to string variable mondayTemperature String mondayTemperature = '4'; //Pass mondayTemperature i.e.String “4” as a parameter to valueOf() //to convert string 'mondayTemperature ' value to integer //and assign it to Integer variable mondayTemperature Integer mondayTemperatureValue = Integer.valueOf(mondayTemperature); System.out.println('Monday Temperature value --->'+ mondayTemperatureValue); //Assign text '+6' i.e.value with ‘+’ sign to string variable //tuesdayTemperature String tuesdayTemperature = '+6'; //Pass tuesdayTemperature i.e.String “+6” as a parameter to valueOf() //to convert string 'tuesdayTemperature' value to integer //and assign it to Integer variable tuesdayTemperature Integer tuesdayTemperatureValue = Integer.valueOf(tuesdayTemperature); System.out.println('Tuesday Temperature value --->'+ tuesdayTemperatureValue); //Calculate Average value of 3 days temperature //avgTEmp = (-2+4+(+6))/3 = 8/3 = 2 Integer averageTemperatureValue = (sundayTemperatureValue+mondayTemperatureValue +tuesdayTemperatureValue)/3; //convert z to string just by using '+' operator and appending '' String averageTemperature = averageTemperatureValue+''; //Print string value of x System.out.println('Average Temperature over 3 days --->'+averageTemperature); } }
プログラムの出力は次のとおりです。
日曜日の気温値—>-2
月曜日の気温値—> 4
火曜日の温度値—> 6
3日間の平均気温—> 2
運動: 上記のように文字列値を変換できる場合は、小数点のある文字列を試すことができます
例えば、 「-2」の代わりに「-2.5」を試すことはできますか?
String sundayTemperature =“ -2.5”;を割り当てたparseInt()またはvalueOf()メソッドを使用して上記のサンプルコードを試してください。
ヒント: 解析可能な値について、メソッドのシグネチャをもう一度読んでください。
回答: 上記のサンプルプログラムをStringで試してみると 日曜日温度 =“ -2.5、parseInt()およびvalueOf()のString引数の値がASCIIプラス「+」またはマイナス「-」の符号と10進数であるため、NumberFormatExceptionがスローされます。
したがって、明らかに「。」は無効です。また、これら2つのメソッドはIntegerクラスによって提供されるため、「2.5」のような浮動小数点値は、これらのメソッドの解析不可能な値になります。
したがって、Javaで文字列をintに変換するためのIntegerクラスの両方のメソッドについて説明しました。
Javaで文字列をIntに変換することに関するFAQ
Q#1)JavaでStringをintに変換するにはどうすればよいですか?
回答: Javaでは、文字列から整数への変換は、次の整数クラスメソッドのメソッドを使用するという2つの方法を使用して実行できます。
- Integer.parseInt()
- Integer.valueOf()
Q#2)整数をどのように解析しますか?
回答: 整数クラスは、整数値を解析して文字列をint値に変換するために使用される静的メソッド、つまりparseInt()およびvalueOf()を提供します。
Q#3)parseInt()とは何ですか?
回答: parseInt()は、Java文字列をint値に変換するために使用されるIntegerクラスによって提供される静的メソッドであり、String値が引数として渡され、整数値がメソッドによって返されます。
例えば、 int x = Integer.parseInt(“ 100”)はint値100を返します
Q#4)Javaでの解析とは何ですか?
回答: Javaでの解析は、基本的に、あるデータ型のオブジェクトの値を別のデータ型に変換することです。 例えば、 Integer.valueOf(str)は、Stringデータ型のオブジェクトである「str」を整数データ型オブジェクトに変換します。
結論
このチュートリアルでは、次のラッパークラスの整数静的メソッドを使用して、JavaでStringをintに変換する方法について説明しました。
- Integer.parseInt()
- Integer.valueOf()
また、無効な数値文字列に対してNumberFormatExceptionがスローされる場合についても説明しました。
さらに読む= >> Javaで整数をStingに変換する8つのメソッド
=> ここでシンプルなJavaトレーニングシリーズをご覧ください