web-dev-qa-db-ja.com

JavaでStringをintに変換する方法

JavaでStringintに変換する方法を教えてください。

私の文字列は数字だけを含んでいるので、私はそれが表す数字を返したいと思います。

たとえば、文字列"1234"を指定すると、結果は数値1234になります。

2781
Unknown user
String myString = "1234";
int foo = Integer.parseInt(myString);

Java Documentation を見ると、 "catch"はこの関数がNumberFormatExceptionを投げることができるということに気づくでしょう。もちろん、これを処理しなければなりません。

int foo;
try {
   foo = Integer.parseInt(myString);
}
catch (NumberFormatException e)
{
   foo = 0;
}

(この処理はデフォルトで0に誤った形式の数値を与えますが、あなたが好きなら他のことをすることができます。)

あるいは、GuavaライブラリのIntsメソッドを使用することもできます。これは、Java 8のOptionalと組み合わせて、文字列をintに変換する強力で簡潔な方法になります。

import com.google.common.primitives.Ints;

int foo = Optional.ofNullable(myString)
 .map(Ints::tryParse)
 .orElse(0)
3787
Rob Hruska

たとえば、これは2つの方法です。

Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);

これらの方法にはわずかな違いがあります。 

  • valueOfは、Java.lang.Integerの新規またはキャッシュされたインスタンスを返します
  • parseIntはプリミティブintを返します。 

Short.valueOf/parseShortLong.valueOf/parseLongなど、すべての場合に同じことが言えます。

629
smas

考慮すべき非常に重要な点は、 Javadoc に記述されているように、Integerパーサーが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.
}

分割引数から整数値を取得しようとしたり、何かを動的に解析したりするときは、この例外を処理することが重要です。

230
Ali Akdurak

手動で実行してください。

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;
}
83
Billz

現在私は大学のために課題をやっています、ここで私は上のもののような特定の表現を使うことができない、そしてASCIIテーブルを見ることによって、私はそれをすることができました。これははるかに複雑なコードですが、私のように制限されている他の人に役立つ可能性があります。

最初にやるべきことは、入力、この場合は数字列を受け取ることです。私はそれをString numberと呼びます、そしてこの場合、私はそれを数字12を使って例示します、それでString number = "12";

もう一つの制限は、私は繰り返しのサイクルを使うことができなかったという事実でした、それで、(それは完璧であったであろう)forサイクルもまた使うことができません。これで少し制限がありますが、これもまた目標です。 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に変換する必要があります。できることはありません。

このようにして、後者(最後の桁)を2/10 = 0.2のように(したがってなぜ2倍に)10で割ることになります。

 lastdigit = lastdigit/10;

これは単に数字で遊んでいます。最後の桁を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のような「マジック」表現はありません
42
Oak

代わりの解決策は Apache Commons ' NumberUtilsを使うことです。

int num = NumberUtils.toInt("1234");

文字列が無効な数値形式の場合は常に0が返されるため、ApacheユーティリティはNiceです。そのため、try catchブロックを節約できます。

Apache NumberUtils APIバージョン3.4

40
Ryboflavin

Integer.decode

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

intの代わりにIntegerを取得したい場合は、次のようにします。

  1. ボックス化解除:

    int val = Integer.decode("12"); 
    
  2. intValue()

    Integer.decode("12").intValue();
    
32

与えられたStringがIntegerを含まないという可能性がごくわずかである場合はいつでも、この特別なケースを処理しなければなりません。残念ながら、標準のJavaメソッドInteger::parseIntおよびInteger::valueOfは、この特殊なケースを知らせるために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));

これはまだフロー制御のために例外を内部的に使用していますが、用法コードは非常にきれいになります。

25
Stefan Dollase

文字列をintに変換することは、単に数値を変換することよりも複雑です。あなたは以下の問題について考えています:

  • 文字列に含まれるのは数字だけですか 0-9
  • 文字列の前後の - /+ はどうなっていますか?それは可能ですか(会計番号を参照)。
  • MAX _-/MIN_INFINITYはどうなっていますか? 文字列が99999999999999999999の場合はどうなりますか?マシンはこの文字列をintとして扱うことができますか?
23
Dennis Ahaus

その方法:

 1. Integer.parseInt(s)
 2. Integer.parseInt(s, radix)
 3. Integer.parseInt(s, beginIndex, endIndex, radix)
 4. Integer.parseUnsignedInt(s)
 5. Integer.parseUnsignedInt(s, radix)
 6. Integer.parseUnsignedInt(s, beginIndex, endIndex, radix)
 7. Integer.valueOf(s)
 8. Integer.valueOf(s, radix)
 9. Integer.decode(s)
 10. NumberUtils.toInt(s)
 11. NumberUtils.toInt(s, defaultValue)

Integer.valueOfはIntegerオブジェクト、その他すべてのメソッド - プリミティブintを生成します。

commons-lang3からの最後の2つの方法 そして変換についての大きな記事 ここ .

22

String値を整数値に変換するためにIntegerラッパークラスのparseInt(String str)メソッドを使うことができます。

例えば:

String strValue = "12345";
Integer intValue = Integer.parseInt(strVal);

IntegerクラスはvalueOf(String str)メソッドも提供します。

String strValue = "12345";
Integer intValue = Integer.valueOf(strValue);

NumberUtilsユーティリティクラスtoInt(String strValue)を変換に使用することもできます。

String strValue = "12345";
Integer intValue = NumberUtils.toInt(strValue);
22
Giridhar Kumar

Integer.parseInt(yourString) を使用 

以下のことを忘れないでください。

Integer.parseInt("1"); // ok

Integer.parseInt("-1"); // ok

Integer.parseInt("+1"); // ok

Integer.parseInt(" 1"); //例外(空白)

Integer.parseInt("2147483648"); //例外(整数は 最大値 2,147,483,647に制限されています)

Integer.parseInt("1.1"); //例外(またはまたは許可されていないもの)

Integer.parseInt(""); //例外(0以外)

例外の種類は1つだけです。 NumberFormatException

19
Lukas Bauer

私は解決策を持っていますが、それがどれほど効果的かはわかりません。しかし、それはうまくいきます、そして私はあなたがそれを改善することができると思います。一方で、私は 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));
        }
    }
}
19
fitorec

楽しみのために:OptionalStringに変換するためにJava 8のIntegerを使うことができます。

String str = "123";
Integer value = Optional.of(str).map(Integer::valueOf).get();
// Will return the integer value of the specified string, or it
// will throw an NPE when str is null.

value = Optional.ofNullable(str).map(Integer::valueOf).orElse(-1);
// Will do the same as the code above, except it will return -1
// when srt is null, instead of throwing an NPE.

ここではInteger.valueOfOptinalを組み合わせるだけです。おそらくこれが便利な状況があるかもしれません - 例えば、nullチェックを避けたい場合などです。 Java 8以前のコードは次のようになります。

Integer value = (str == null) ? -1 : Integer.parseInt(str);
17
Anton Balaniuc

Guavaには tryParse(String) があります。これは、文字列を解析できなかった場合にnullを返します。

Integer fooInt = Ints.tryParse(fooString);
if (fooInt != null) {
  ...
}
16

数字以外のすべての文字を削除してからintを解析することから始めることもできます。

string mystr = mystr.replaceAll( "[^\\d]", "" );
int number= Integer.parseInt(mystr);

しかし、これは負でない数に対してのみ有効であることに注意してください。 

14
Thijser

上記の答えとは別に、いくつかの機能を追加したいと思います。 

    public static int parseIntOrDefault(String value, int defaultValue) {
    int result = defaultValue;
    try {
      result = Integer.parseInt(value);
    } catch (Exception e) {

    }
    return result;
  }

  public static int parseIntOrDefault(String value, int beginIndex, int defaultValue) {
    int result = defaultValue;
    try {
      String stringValue = value.substring(beginIndex);
      result = Integer.parseInt(stringValue);
    } catch (Exception e) {

    }
    return result;
  }

  public static int parseIntOrDefault(String value, int beginIndex, int endIndex, int defaultValue) {
    int result = defaultValue;
    try {
      String stringValue = value.substring(beginIndex, endIndex);
      result = Integer.parseInt(stringValue);
    } catch (Exception e) {

    }
    return result;
  }

実行中の結果は次のとおりです。 

  public static void main(String[] args) {
    System.out.println(parseIntOrDefault("123", 0)); // 123
    System.out.println(parseIntOrDefault("aaa", 0)); // 0
    System.out.println(parseIntOrDefault("aaa456", 3, 0)); // 456
    System.out.println(parseIntOrDefault("aaa789bbb", 3, 6, 0)); // 789
  }
12
nxhoaf

あなたが確実に数字が常に有効な整数になると確信しているプログラミング競技会では、あなたは入力を解析するためにあなた自身のメソッドを書くことができます。これはすべての検証関連のコードをスキップし(あなたはそれを必要としないので)、もう少し効率的になります。

  1. 有効な正の整数の場合

    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;
    }
    
  2. 正の整数と負の整数の両方に対して:

    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;
    }
    

  3. これらの数字の前後に空白があると予想される場合は、さらに処理する前にstr = str.trim()を実行してください。

9
Raman Sahasi

すでに述べたように、Apache Commons NumberUtilsがそれを実行できます。文字列をintに変換できない場合は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; 
9
Alireza Fattahi

いくつかの注意を払って、このコードも使用できます。

  • オプション1:メッセージダイアログを表示して現在のワークフローの実行を停止するなど、例外を明示的に処理します。例えば:

    try
        {
            String stringValue = "1234";
    
            // From String to Integer
            int integerValue = Integer.valueOf(stringValue);
    
            // Or
            int integerValue = Integer.ParseInt(stringValue);
    
            // Now from integer to back into string
            stringValue = String.valueOf(integerValue);
        }
    catch (NumberFormatException ex) {
        //JOptionPane.showMessageDialog(frame, "Invalid input string!");
        System.out.println("Invalid input string!");
        return;
    }
    
  • オプション2:例外が発生した場合に実行フローを続行できる場合は、影響を受ける変数をリセットします。たとえば、catchブロックにいくつかの変更を加えます。

    catch (NumberFormatException ex) {
        integerValue = 0;
    }
    

比較や計算のために文字列定数を使用することは、常に良い考えです。定数はnull値を返さないからです。

9
manikant gautam

new Scanner("1244").nextInt()を使うことができます。あるいはintが存在するかどうかを尋ねます:new Scanner("1244").hasNextInt()

9
int foo=Integer.parseInt("1234");

文字列に数値以外のデータが含まれていないことを確認してください。

7
iKing

通常の文字列の場合は、次のものを使用できます。

int number = Integer.parseInt("1234");

String builderとString bufferの場合は、次のものを使用できます。

Integer.parseInt(myBuilderOrBuffer.toString());
7
Aditya

単にこれを試すことができます:

  • Stringintに変換するにはInteger.parseInt(your_string);を使用してください。
  • Stringdoubleに変換するにはDouble.parseDouble(your_string);を使用してください。

String str = "8955";
int q = Integer.parseInt(str);
System.out.println("Output>>> " + q); // Output: 8955

String str = "89.55";
double q = Double.parseDouble(str);
System.out.println("Output>>> " + q); // Output: 89.55
7
Vishal Yadav

さあ

String str="1234";
int number = Integer.parseInt(str);
print number;//1234
6
Shivanandam

StringをパラメータとするIntegerコンストラクタについて言及していないことに少し驚いています。
だから、ここにあります: 

String myString = "1234";
int i1 = new Integer(myString);

Java 8 - 整数(文字列) 。 

もちろん、コンストラクターはInteger型を返し、アンボックス化操作は値をintに変換します。 


言及することは重要です
このコンストラクタはparseIntメソッドを呼び出します。 

public Integer(String var1) throws NumberFormatException {
    this.value = parseInt(var1, 10);
}
6
djm.im

整数以外の文字が入力された場合に備えて、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);
    }
 }
5
David

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);
5
Pankaj Mandale

これはライブラリを使用せずにすべての条件が正、負の条件を持つ完全なプログラムです  

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;
     }
    }
4
Anup Gupta

Integer.parseInt(myString); - ラッパークラスを使う

3
Phani Kumar

5つの方法で行うことができます:

import com.google.common.primitives.Ints;
import org.Apache.commons.lang.math.NumberUtils;

1)Ints.tryParseを使う:

String number = "999";
int result = Ints.tryParse(number);

2)NumberUtils.createIntegerを使う:

String number = "999";
Integer result = NumberUtils.createInteger(number);

3)NumberUtils.toIntを使う:

String number = "999";
int result = NumberUtils.toInt(number);

4)Integer.valueOfを使う:

String number = "999";
Integer result = Integer.valueOf(number);

5)Integer.parseIntを使う:

String number = "999";
int result = Integer.parseInt(number);
3
Santosh Jadi

ちなみに、文字列がnullの場合は、次の呼び出しを行います。

int i = Integer.parseInt(null);

nullPointerExceptionではなく、NumberFormatExceptionをスローします。

3
Pavel Molchanov

あなたは以下のうちのどれでも使うことができました: 

  1. Integer.parseInt(s)
  2. Integer.parseInt(s, radix)
  3. Integer.parseInt(s, beginIndex, endIndex, radix)
  4. Integer.parseUnsignedInt(s)
  5. Integer.parseUnsignedInt(s, radix)
  6. Integer.parseUnsignedInt(s, beginIndex, endIndex, radix)
  7. Integer.valueOf(s)
  8. Integer.valueOf(s, radix)
  9. Integer.decode(s)
  10. NumberUtils.toInt(s)
  11. NumberUtils.toInt(s, defaultValue)
2
Rajeev Ranjan

import Java.util。*;

パブリッククラスstrToint {

    public static void main(String[] args){

            String str = "123";

            byte barr[] = str.getBytes();

            System.out.println(Arrays.toString(barr));
            int result=0;
            for(int i=0;i<barr.length;i++){
                    //System.out.print(barr[i]+" ");
                    int ii = barr[i];
                    char a = (char)ii;
                    int no = Character.getNumericValue(a);
                    result=result*10+no;
                    System.out.println(result);

            }
            System.out.println("result:"+result);
    }

}

2
Abhijeet Kale

public static int parseInt(String s)はNumberFormatExceptionをスローします

Integer.parseInt()を使ってStringをintに変換することができます。

string 20をプリミティブint型に変換します。

    String n = "20";
    int r = Integer.parseInt(n);//returns a primitive int       
    System.out.println(r);

出力20

文字列が解析可能な整数を含まない場合それはNumberFormatExceptionを投げます

String n = "20I";// throwns NumberFormatException
int r = Integer.parseInt(n);
System.out.println(r);

public static Integer valueOf(String s)がNumberFormatExceptionをスローします

あなたはInteger.valueOf()を使うことができます、これでそれはIntegerオブジェクトを返します。

String n = "20";
Integer r = Integer.valueOf(n); //returns a new Integer() object.   
System.out.println(r);

出力20

参照先 https://docs.Oracle.com/en/

StringIntに変換する方法のいくつかは次のとおりです。

  1. Integer.parseInt()を使うことができます:

    String test = "4568"; int new = Integer.parseInt(test);

  2. Integer.valueOf()を使うこともできます。

    String test = "4568"; int new =Integer.parseInt(test);

0

Java IntegerクラスのparseIntメソッドを使用して文字列を整数に変換します。 parseIntメソッドは、Stringをintに変換し、ストリングをint型に変換できない場合はNumberFormatExceptionをスローします。

それが投げることができる例外を見逃して、これを使ってください:

int i = Integer.parseInt(myString);

変数myStringで示されるStringが“1234”, “200”, “1”,のような有効な整数であり、それがJavaのintに変換される場合。なんらかの理由で失敗した場合、変更によってNumberFormatExceptionがスローされる可能性があるため、これを考慮するためにコードをもう少し長くする必要があります。

例JavaのStringからintへの変換メソッド、可能なNumberFormatExceptionの制御

public class JavaStringToIntExample
{
  public static void main (String[] args)
  {
    // String s = "test";  // use this if you want to test the exception below
    String s = "1234";

    try
    {
      // the String to int conversion happens here
      int i = Integer.parseInt(s.trim());

      // print out the value after the conversion
      System.out.println("int i = " + i);
    }
    catch (NumberFormatException nfe)
    {
      System.out.println("NumberFormatException: " + nfe.getMessage());
    }
  }
}

変更の試みが失敗した場合 - Java Stringテストをintに変換しようとした場合 - 整数parseIntプロセスはNumberFormatExceptionをスローします。これはtry/catchブロックで処理する必要があります。

0
Nisarg

あなたはparseIntメソッドを使用することができます  

  String SrNumber="5790";
int extractNumber = Integer.parseInt(SrNumber);
System.out.println(extractNumber);//Result will be --5790
0

カスタムアルゴリズム:

public static int toInt(String value) {
  int output = 0;
  boolean isFirstCharacter = true;
  boolean isNegativeNumber = false;
  byte bytes[] = value.getBytes();
  for (int i = 0; i < bytes.length; i++) {
    char c = (char) bytes[i];
    if (!Character.isDigit(c)) {
      isNegativeNumber = (c == '-');
      if (!(isFirstCharacter && (isNegativeNumber || c == '+'))) {
        throw new NumberFormatException("For input string \"" + value + "\"");
      }
    } else {
      int number = Character.getNumericValue(c);
      output = output * 10 + number;
    }
    isFirstCharacter = false;
  }
  if (isNegativeNumber) output *= -1;
  return output;
}

他の解決策: (文字列をバイト配列に変換する代わりに文字列 charAt メソッドを使う):

public static int toInt(String value) {
  int output = 0;
  boolean isFirstCharacter = true;
  boolean isNegativeNumber = false;
  for (int i = 0; i < value.length(); i++) {
    char c = value.charAt(i);
    if (!Character.isDigit(c)) {
      isNegativeNumber = (c == '-');
      if (!(isFirstCharacter && (isNegativeNumber || c == '+'))) {
        throw new NumberFormatException("For input string \"" + value + "\"");
      }
    } else {
      int number = Character.getNumericValue(c);
      output = output * 10 + number;
    }
    isFirstCharacter = false;
  }
  if (isNegativeNumber) output *= -1;
  return output;
}

例:

int number1 = toInt("20");
int number2 = toInt("-20");
int number3 = toInt("+20");
System.out.println("Numbers = " + number1 + ", " + number2 + ", " + number3);

try {
  toInt("20 Hadi");
} catch (NumberFormatException e) {
  System.out.println("Error: " + e.getMessage());
}
0
nabeghe

メソッドを使う:Integer.parseInt(String s)

String s = "123";
int n = Integer.parseInt(s);
0
karthik_varma_k

Integer.parseInt()を使用してください。これは文字列値をintに解析するのに役立ちます。

例:

String str = "2017";
int i = Integer.parseInt(str);
System.out.println(i);

出力: 2017

0
Alekya

この方法を使用してください。

public int ConvertStringToInt(String number)
{
 int num = 0;
 try
 {
   int newNumber = Integer.ParseInt(number);
   num = newNumber;
 }
 catch(Exception ex)
 {
   num = 0;
   Log.i("Console",ex.toString);
 }
   return num;
}
0
mohamad sheikhi

Stringをさまざまに入力してこのコードを試してください。

String a = "10";  
String a = "10ssda";  
String a = null; 
String a = "12102";

if(null != a) {
    try {
        int x = Integer.ParseInt(a.trim()); 
        Integer y = Integer.valueOf(a.trim());
        //  It will throw a NumberFormatException in case of invalid string like ("10ssda" or "123 212") so, put this code into try catch
    } catch(NumberFormatException ex) {
        // ex.getMessage();
    }
}
0
Ram Chhabra

私は文字列入力をintかlongにパースするためのこの速い方法を書きました。現在のJDK 11のInteger.parseIntまたはLong.parseLongより速いです。あなたはintを要求しただけですが、私はロングパーサも含めました。以下のコードパーサーは、それが速く動作するためにパーサーのメソッドが小さいことを要求します。代替バージョンはテストコードの下にあります。代替バージョンはかなり速く、そしてそれはクラスのサイズに依存しません。

このクラスはオーバーフローをチェックし、あなたはあなたのニーズに適応するようにコードをカスタマイズすることができます。空の文字列は私の方法では0になりますが、それは意図的なものです。あなたはあなたのケースを適応させるためにそれを変更するか、またはそのまま使用することができます。 

これはparseIntとparseLongが必要とされるクラスの一部です。これは基数10の数値のみを扱うことに注意してください。

Intパーサのテストコードは以下のコードの下にあります。 

/*
 * Copyright 2019 Khang Hoang Nguyen
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 * @author: Khang Hoang Nguyen - [email protected].
 **/
final class faiNumber{        
    private static final long[] longpow = {0L, 1L, 10L, 100L, 1000L, 10000L, 100000L, 1000000L, 10000000L, 100000000L, 1000000000L,
                                           10000000000L, 100000000000L, 1000000000000L, 10000000000000L, 100000000000000L,
                                           1000000000000000L, 10000000000000000L, 100000000000000000L, 1000000000000000000L,
                                           };

    private static final int[] intpow = { 0, 1, 10, 100, 1000, 10000,
                                          100000, 1000000, 10000000, 100000000, 1000000000 
                                        };

    /**
     * parseLong(String str) parse a String into Long. 
     * All errors throw by this method is NumberFormatException.
     * Better errors can be made to tailor to each use case.
     **/
    public static long parseLong(final String str) { 
        final int length = str.length();
        if ( length == 0 ) return 0L;        

        char c1 = str.charAt(0); int start;

        if ( c1 == '-' || c1 == '+' ){
            if ( length == 1 ) throw new NumberFormatException( String.format("Not a valid long value. Input '%s'.", str) );
            start = 1;
        } else {
            start = 0;
        }
        /*
         * Note: if length > 19, possible scenario is to run through the string 
         * to check whether the string contains only valid digits.
         * If the check had only valid digits then a negative sign meant underflow, else, overflow.
         */
        if ( length - start > 19 ) throw new NumberFormatException( String.format("Not a valid long value. Input '%s'.", str) );

        long c; 
        long out = 0L;

        for ( ; start < length; start++){
            c = (str.charAt(start) ^ '0');
            if ( c > 9L ) throw new NumberFormatException( String.format("Not a valid long value. Input '%s'.", str) );
            out += c * longpow[length - start];
        }

        if ( c1 == '-' ){
            out = ~out + 1L;
            // if out > 0 number underflow(supposed to be negative).
            if ( out > 0L ) throw new NumberFormatException( String.format("Not a valid long value. Input '%s'.", str) );
            return out;
        }
        // if out < 0 number overflow(supposed to be positive).
        if ( out < 0L ) throw new NumberFormatException( String.format("Not a valid long value. Input '%s'.", str) );
        return out;
    }

    /**
     * parseInt(String str) parse a string into an int.
     * return 0 if string is empty. 
     **/
    public static int parseInt(final String str) { 
        final int length = str.length();
        if ( length == 0 ) return 0;        

        char c1 = str.charAt(0); int start; 

        if ( c1 == '-' || c1 == '+' ){
            if ( length == 1 ) throw new NumberFormatException( String.format("Not a valid integer value. Input '%s'.", str) );
            start = 1;
        } else {
            start = 0;
        }

        int out = 0; int c;
        int runlen = length - start;

        if ( runlen > 9 ) {
            if ( runlen > 10 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );

            c = (str.charAt(start) ^ '0');   // <- Any number from 0 - 255 ^ 48 will yield greater than 9 except 48 - 57
            if ( c > 9 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
            if ( c > 2 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
            out += c * intpow[length - start++];
        }

        for ( ; start < length; start++){
            c = (str.charAt(start) ^ '0');
            if ( c > 9 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
            out += c * intpow[length - start];
        }

        if ( c1 == '-' ){
            out = ~out + 1;
            if ( out > 0 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
            return out;
        }

        if ( out < 0 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
        return out;
    }
}

テストコードセクションこれには約200秒かかります。

// Int Number Parser Test;
long start = System.currentTimeMillis();    
System.out.println("INT PARSER TEST");
for (int i = Integer.MIN_VALUE; i != Integer.MAX_VALUE; i++){
   if( faiNumber.parseInt(""+i) != i ) System.out.println("Wrong");
   if ( i == 0 ) System.out.println("HalfWay Done");
}

if( faiNumber.parseInt(""+Integer.MAX_VALUE) != Integer.MAX_VALUE ) System.out.println("Wrong");
long end = System.currentTimeMillis();
long result = (end - start);
System.out.println(result);        
// INT PARSER END */

また非常に速い代替方法。 int powの配列は使用されていませんが、ビットシフトによる10倍の乗算の数学的最適化に注意してください。

public static int parseInt(final String str) { 
    final int length = str.length();
    if ( length == 0 ) return 0;        

    char c1 = str.charAt(0); int start; 

    if ( c1 == '-' || c1 == '+' ){
        if ( length == 1 ) throw new NumberFormatException( String.format("Not a valid integer value. Input '%s'.", str) );
        start = 1;
    } else {
        start = 0;
    }

    int out = 0; int c;
    while( start < length && str.charAt(start) == '0' ) start++; // <-- This to disregard leading 0, can be removed if you know exactly your source does not have leading zeroes.
    int runlen = length - start;

    if ( runlen > 9 ) {
        if ( runlen > 10 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );

        c = (str.charAt(start++) ^ '0');   // <- Any number from 0 - 255 ^ 48 will yield greater than 9 except 48 - 57
        if ( c > 9 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
        if ( c > 2 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
        out = (out << 1) + (out << 3) + c; // <- alternatively this can just be out = c or c above can just be out;
    }

    for ( ; start < length; start++){
        c = (str.charAt(start) ^ '0');
        if ( c > 9 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
        out = (out << 1) + (out << 3) + c; 
    }

    if ( c1 == '-' ){
        out = ~out + 1;
        if ( out > 0 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
        return out;
    }

    if ( out < 0 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
    return out;
}
0
Kevin Ng