配列 - オブジェクト int 変換 java
Javaで文字列をintに変換するにはどうすればよいですか? (20)
JavaでString
をint
に変換するにはどうすればよいですか?
My Stringには数字だけが含まれていて、その数字が返されるようにしたい。
たとえば、文字列"1234"
が指定された場合、結果は数字1234
ます。
Integer.decode
また、 public static Integer decode(String nm) throws NumberFormatException
することができpublic static Integer decode(String nm) throws NumberFormatException
。
ベース8と16でも動作します:
// base 10
Integer.parseInt("12"); // 12 - int
Integer.valueOf("12"); // 12 - Integer
Integer.decode("12"); // 12 - Integer
// base 8
// 10 (0,1,...,7,10,11,12)
Integer.parseInt("12", 8); // 10 - int
Integer.valueOf("12", 8); // 10 - Integer
Integer.decode("012"); // 10 - Integer
// base 16
// 18 (0,1,...,F,10,11,12)
Integer.parseInt("12",16); // 18 - int
Integer.valueOf("12",16); // 18 - Integer
Integer.decode("#12"); // 18 - Integer
Integer.decode("0x12"); // 18 - Integer
Integer.decode("0X12"); // 18 - Integer
// base 2
Integer.parseInt("11",2); // 3 - int
Integer.valueOf("11",2); // 3 - Integer
Integer
代わりにint
を取得したい場合は、以下を使用できます:
アンボクシング:
int val = Integer.decode("12");
intValue()
:Integer.decode("12").intValue();
1つの方法は、parseInt(String)はプリミティブintを返します。
String number = "10";
int result = Integer.parseInt(number);
System.out.println(result);
2番目の方法は、valueOf(String)が新しいInteger()オブジェクトを返すことです。
String number = "10";
Integer result = Integer.valueOf(number);
System.out.println(result);
Integer.parseInt()を使用してtry...catch
ブロックの中に入れて、数字以外の文字が入力された場合のエラーを処理します。たとえば、
private void ConvertToInt(){
String string = txtString.getText();
try{
int integerValue=Integer.parseInt(string);
System.out.println(integerValue);
}
catch(Exception e){
JOptionPane.showMessageDialog(
"Error converting string to integer\n" + e.toString,
"Error",
JOptionPane.ERROR_MESSAGE);
}
}
String値を整数値に変換するために、 Integer
ラッパークラスのparseInt(String str)
メソッドを使用できます。
例えば:
String strValue = "12345";
Integer intValue = Integer.parseInt(strVal);
Integer
クラスは、 valueOf(String str)
メソッドも提供しvalueOf(String str)
。
String strValue = "12345";
Integer intValue = Integer.valueOf(strValue);
NumberUtilsユーティリティクラスの toInt(String strValue)
を変換に使用することもできます。
String strValue = "12345";
Integer intValue = NumberUtils.toInt(strValue);
new Scanner("1244").nextInt()
を使うことができます。 new Scanner("1244").hasNextInt()
これは、ライブラリを使用せずにすべての条件が正、負である完全なプログラムです
import java.util.Scanner;
public class StringToInt {
public static void main(String args[]) {
String inputString;
Scanner s = new Scanner(System.in);
inputString = s.nextLine();
if (!inputString.matches("([+-]?([0-9]*[.])?[0-9]+)")) {
System.out.println("Not a Number");
} else {
Double result2 = getNumber(inputString);
System.out.println("result = " + result2);
}
}
public static Double getNumber(String number) {
Double result = 0.0;
Double beforeDecimal = 0.0;
Double afterDecimal = 0.0;
Double afterDecimalCount = 0.0;
int signBit = 1;
boolean flag = false;
int count = number.length();
if (number.charAt(0) == '-') {
signBit = -1;
flag = true;
} else if (number.charAt(0) == '+') {
flag = true;
}
for (int i = 0; i < count; i++) {
if (flag && i == 0) {
continue;
}
if (afterDecimalCount == 0.0) {
if (number.charAt(i) - '.' == 0) {
afterDecimalCount++;
} else {
beforeDecimal = beforeDecimal * 10 + (number.charAt(i) - '0');
}
} else {
afterDecimal = afterDecimal * 10 + number.charAt(i) - ('0');
afterDecimalCount = afterDecimalCount * 10;
}
}
if (afterDecimalCount != 0.0) {
afterDecimal = afterDecimal / afterDecimalCount;
result = beforeDecimal + afterDecimal;
} else {
result = beforeDecimal;
}
return result * signBit;
}
}
さあ
String str="1234";
int number = Integer.parseInt(str);
print number;//1234
それを手動で行う:
public static int strToInt( String str ){
int i = 0;
int num = 0;
boolean isNeg = false;
//Check for negative sign; if it's there, set the isNeg flag
if (str.charAt(0) == '-') {
isNeg = true;
i = 1;
}
//Process each character of the string;
while( i < str.length()) {
num *= 10;
num += str.charAt(i++) - '0'; //Minus the ASCII code of '0' to get the value of the charAt(i++).
}
if (isNeg)
num = -num;
return num;
}
たとえば、次の2つの方法があります。
Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);
これらの方法には若干の違いがあります。
-
valueOf
は、java.lang.Integer
新しいインスタンスまたはキャッシュされたインスタンスを返しjava.lang.Integer
-
parseInt
はプリミティブint
返します。
Short.valueOf
/ parseShort
、 Short.valueOf
/ parseShort
などすべての場合も同じです。
ちなみに、文字列がnullの場合、呼び出しは次のようになります。
int i = Integer.parseInt(null);
NumberFormatExceptionをスローします.NullPointerExceptionはスローしません。
まあ、考慮すべき非常に重要な点は、IntegerパーサーがJavadoc述べたようにNumberFormatExceptionをスローすることです。
int foo;
String StringThatCouldBeANumberOrNot = "26263Hello"; //will throw exception
String StringThatCouldBeANumberOrNot2 = "26263"; //will not throw exception
try {
foo = Integer.parseInt(StringThatCouldBeANumberOrNot);
} catch (NumberFormatException e) {
//Will Throw exception!
//do something! anything to handle the exception.
}
try {
foo = Integer.parseInt(StringThatCouldBeANumberOrNot2);
} catch (NumberFormatException e) {
//No problem this time, but still it is good practice to care about exceptions.
//Never trust user input :)
//Do something! Anything to handle the exception.
}
分割された引数から整数値を取得しようとしたり、何かを動的に解析しようとするとき、この例外を処理することが重要です。
プログラミング競技では、数字が常に有効な整数であることが保証されているので、入力を解析する独自のメソッドを書くことができます。 これにより、検証に関連するすべてのコードがスキップされます(その必要がないため)、もう少し効率的になります。
有効な正の整数の場合:
private static int parseInt(String str) { int i, n = 0; for (i = 0; i < str.length(); i++) { n *= 10; n += str.charAt(i) - 48; } return n; }
正と負の整数の場合:
private static int parseInt(String str) { int i=0, n=0, sign=1; if(str.charAt(0) == '-') { i=1; sign=-1; } for(; i<str.length(); i++) { n*=10; n+=str.charAt(i)-48; } return sign*n; }
これらの数値の前後に空白がある場合は、さらに処理する前に
str = str.trim()
を実行してください。
別の解決方法は、 Apache Commonsの NumberUtilsを使用することです。
int num = NumberUtils.toInt("1234");
文字列が無効な数値形式の場合は、常に0が返されるため、Apacheユーティリティが便利です。 したがって、try catchブロックを保存します。
前述したように、Apache Commons NumberUtils
はそれを行うことができます。 文字列をintに変換できない場合は0
を返し0
。
独自のデフォルト値を定義することもできます。
NumberUtils.toInt(String str, int defaultValue)
例:
NumberUtils.toInt("3244", 1) = 3244
NumberUtils.toInt("", 1) = 1
NumberUtils.toInt(null, 5) = 5
NumberUtils.toInt("Hi", 6) = 6
NumberUtils.toInt(" 32 ", 1) = 1 //space in numbers are not allowed
NumberUtils.toInt(StringUtils.trimToEmpty( " 32 ",1)) = 32;
指定されたStringにIntegerが含まれていない可能性がある場合は、この特殊なケースを処理する必要があります。 悲しいことに、標準のJavaメソッドInteger::parseInt
とInteger::valueOf
は、この特殊なケースを通知するためにNumberFormatException
をスローしNumberFormatException
。 したがって、フロー制御の例外を使用する必要があります。これは、一般的に不適切なコーディングスタイルとみなされます。
私の意見では、この特殊なケースはOptional<Integer>
返すことによって処理されるべきです。 Javaはそのようなメソッドを提供しないので、私は以下のラッパーを使用します:
private Optional<Integer> tryParseInteger(String string) {
try {
return Optional.of(Integer.valueOf(string));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
使用法:
// prints 1234
System.out.println(tryParseInteger("1234").orElse(-1));
// prints -1
System.out.println(tryParseInteger("foobar").orElse(-1));
これは内部でフロー制御の例外を使用していますが、使用法のコードはきれいになります。
数値以外の文字をすべて削除してから、intを解析することもできます。
string mystr = mystr.replaceAll( "[^\\d]", "" );
int number= Integer.parseInt(mystr);
しかし、これは非負の数値に対してのみ機能することに注意してください。
現在私は、上記のような特定の表現を使用できない大学の課題を行っています。そして、ASCIIテーブルを見て、私はそれをやりました。 はるかに複雑なコードですが、私のように制限された他の人を助けることができます。
最初に行うべきことは、入力(この場合は数字の文字列)を受け取ることです。 私はそれをString number
と呼ぶことにします。この場合、数字12を使用して例を示します。したがって、 String number = "12";
もう1つの制限は、繰り返しサイクルを使用できないという事実でした。したがって、サイクル(完全であったでしょう)でも使用できませんでした。 これは私たちに少し制限を与えますが、それもまた目標です。 私は2桁しか必要としなかったので(最後の2桁を取る)、簡単なcharAt
それを解決しました:
// Obtaining the integer values of the char 1 and 2 in ASCII
int semilastdigitASCII = number.charAt(number.length()-2);
int lastdigitASCII = number.charAt(number.length()-1);
コードがあれば、テーブルを参照して必要な調整をするだけです。
double semilastdigit = semilastdigitASCII - 48; //A quick look, and -48 is the key
double lastdigit = lastdigitASCII - 48;
さて、なぜダブルですか? まあ、本当に "奇妙な"ステップのために。 現在、私たちは1と2の2つの倍数を持っていますが、12にする必要があります。私たちができる数学演算はありません。
後者(lastdigit)を2/10 = 0.2
ように10で除算します(したがって、なぜdoubleであるか)。
lastdigit = lastdigit/10;
これは単に数字で遊んでいるだけです。 最後の桁を小数点に変えていました。 しかし今、何が起こるかを見てください:
double jointdigits = semilastdigit + lastdigit; // 1.0 + 0.2 = 1.2
数学に入ることなく、私たちは単なる数字の数字を単離しています。 あなたは、0〜9だけを考慮しているので、10の倍数で割ることは、あなたがそれを保管する「ボックス」を作成するようなものです。(1級の教師がユニットと100が何であるか説明しました。 そう:
int finalnumber = (int) (jointdigits*10); // Be sure to use parentheses "()"
そして、そこに行く。 次の制限を考慮して、桁の文字列(この場合は2桁)を2桁の整数に変換しました。
- 反復サイクルはありません
- parseIntのような "Magic"式はありません。
私には解決策がありますが、それがどれほど効果的かわかりません。 しかし、それはうまく動作し、あなたはそれを改善できると思います。 一方、私はJUnitといくつかのテストを正しく実行しました。 私は関数とテストを添付:
static public Integer str2Int(String str) {
Integer result = null;
if (null == str || 0 == str.length()) {
return null;
}
try {
result = Integer.parseInt(str);
}
catch (NumberFormatException e) {
String negativeMode = "";
if(str.indexOf('-') != -1)
negativeMode = "-";
str = str.replaceAll("-", "" );
if (str.indexOf('.') != -1) {
str = str.substring(0, str.indexOf('.'));
if (str.length() == 0) {
return (Integer)0;
}
}
String strNum = str.replaceAll("[^\\d]", "" );
if (0 == strNum.length()) {
return null;
}
result = Integer.parseInt(negativeMode + strNum);
}
return result;
}
JUnitでテストする:
@Test
public void testStr2Int() {
assertEquals("is numeric", (Integer)(-5), Helper.str2Int("-5"));
assertEquals("is numeric", (Integer)50, Helper.str2Int("50.00"));
assertEquals("is numeric", (Integer)20, Helper.str2Int("$ 20.90"));
assertEquals("is numeric", (Integer)5, Helper.str2Int(" 5.321"));
assertEquals("is numeric", (Integer)1000, Helper.str2Int("1,000.50"));
assertEquals("is numeric", (Integer)0, Helper.str2Int("0.50"));
assertEquals("is numeric", (Integer)0, Helper.str2Int(".50"));
assertEquals("is numeric", (Integer)0, Helper.str2Int("-.10"));
assertEquals("is numeric", (Integer)Integer.MAX_VALUE, Helper.str2Int(""+Integer.MAX_VALUE));
assertEquals("is numeric", (Integer)Integer.MIN_VALUE, Helper.str2Int(""+Integer.MIN_VALUE));
assertEquals("Not
is numeric", null, Helper.str2Int("czv.,xcvsa"));
/**
* Dynamic test
*/
for(Integer num = 0; num < 1000; num++) {
for(int spaces = 1; spaces < 6; spaces++) {
String numStr = String.format("%0"+spaces+"d", num);
Integer numNeg = num * -1;
assertEquals(numStr + ": is numeric", num, Helper.str2Int(numStr));
assertEquals(numNeg + ": is numeric", numNeg, Helper.str2Int("- " + numStr));
}
}
}
通常の文字列の場合は、次のものを使用できます。
int number = Integer.parseInt("1234");
StringビルダーとStringバッファの場合は、次のものを使用できます。
Integer.parseInt(myBuilderOrBuffer.toString());
String myString = "1234";
int foo = Integer.parseInt(myString);
詳細については、 Javaのマニュアルを参照してください。