Android에서 문자열을 정수로 변환하기

문자열을 정수로 변환하려면 어떻게 하나요?

사용자가 숫자를 입력하도록 하는 텍스트 상자가 있습니다:

EditText et = (EditText) findViewById(R.id.entry1);
String hello = et.getText().toString();

그리고 이 값은 문자열 hello에 할당됩니다.

나중에 코드에서 사용할 수 있도록 정수로 변환하여 사용자가 입력한 숫자를 얻고 싶습니다.

편집 텍스트`를 정수로 가져올 수 있는 방법이 있나요? 그러면 중개자를 건너뛸 수 있습니다. 그렇지 않다면 문자열을 정수로 변환해도 괜찮습니다.

질문에 대한 의견 (1)
해결책

Integer 클래스와 정적 parseInt() 메서드를 참조하세요:

http://developer.android.com/reference/java/lang/Integer.html

Integer.parseInt(et.getText().toString());

구문 분석 중 문제가 발생할 경우 NumberFormatException을 잡아야 합니다:

int myNum = 0;

try {
    myNum = Integer.parseInt(et.getText().toString());
} catch(NumberFormatException nfe) {
   System.out.println("Could not parse " + nfe);
} 
해설 (2)
int in = Integer.valueOf(et.getText().toString());
//or
int in2 = new Integer(et.getText().toString());
해설 (0)
  • 일반 expression:* 사용
String s="your1string2contain3with4number";
int i=Integer.parseInt(s.replaceAll("[\\D]", ""));

출력: i = 1234년;

  • 그럼 첫 번째 숫자는 조합으로의 하는 경우 아래 번호:* 한다.
String s="abc123xyz456";
int i=NumberFormat.getInstance().parse(s).intValue();

출력: i = 123.

해설 (0)
  • 일반 expression:* 사용
int i=Integer.parseInt("hello123".replaceAll("[\\D]",""));
int j=Integer.parseInt("123hello".replaceAll("[\\D]",""));
int k=Integer.parseInt("1h2el3lo".replaceAll("[\\D]",""));
  • output:*
i=123;
j=123;
k=123;
해설 (1)

가장 좋은 방법은 이미 언급한 것처럼 이것을 사용하여 정규식이 아시시 사우

public int getInt(String s){
return Integer.parseInt(s.replaceAll("[\\D]", ""));
}
해설 (0)

이 코드를 시도하시겠습니까 it& # 39 의 상행담관염이라고 작업 중.

int number = 0;
try {
    number = Integer.parseInt(YourEditTextName.getText().toString());
} catch(NumberFormatException e) {
   System.out.println("parse value is not valid : " + e);
} 
해설 (0)

최선의 방법은 int 는 문자열) 로 변환할 수 있습니다.

 EditText et = (EditText) findViewById(R.id.entry1);
 String hello = et.getText().toString();
 int converted=Integer.parseInt(hello);
해설 (0)

정수 다음 문자열 구문 분석을 위해 사용할 수 있습니다.

, int value = 안테거스파르세인트 (테스트비우스게테스트 네스토스트링 () ())

      • (1) 그 input:* 12 작동합니다. 이 때문에 할 수 있다, 12&quot &quot 테스트비에프 12 자리 잡고 있다. 구체화하십시오.
  • (2) input:* &quot abdul"; 즉 누마버포매렉세페시옹 어졌다면 예외가 던져질 것이다. 우리는 이 문제를 해결할 수 있도록 as I catch 시도하시겠습니까 언급하십시오 사용할 필요가 있다 (아래 참조).

  int tax_amount=20;
  EditText edit=(EditText)findViewById(R.id.editText1);
     try
       {

        int value=Integer.parseInt(edit.getText().toString());
        value=value+tax_amount;
        edit.setText(String.valueOf(value));// to convert integer to string 

       }catch(NumberFormatException ee){
       Log.e(ee.toString());
       }

자세한 내용은 아래 링크를 참조할 수도 있습니다. , http://developer.android.com/reference/java/lang/Integer.html

해설 (0)

문자열을 플로트로 숨겨야 합니다. 작동 중입니다.

float result = 0;
 if (TextUtils.isEmpty(et.getText().toString()) {
  return;
}

result = Float.parseFloat(et.getText().toString());

tv.setText(result); 
해설 (0)

한 줄로 할 수도 있습니다.

int hello = Integer.parseInt(((Button)findViewById(R.id.button1)).getText().toString().replaceAll("[\\D]", ""));

판독값 오더할 에서 실행

  1. 핀드비에우베이드 사용하여 볼 '눈' (R. id.button1) 2 '는' 나라를 위해 사용하는 ' ((버튼) _)' 으로 '보기' 버튼을
  2. '콜' () 에서 버튼를 오게테스트 afaq 텍스트 입력
  3. 콜 () '를' 네스토스트링 변환하십시오 문자열으로 다양한 문자
  4. () '을 (를)', '콜' 이어플라치알레 " [\D] &quot 교체할 수 있는 모든 비사양 자리 캐릭터와 &quot "; (없음)
  5. 호출하십시오 안테거스파르세인트 () '정수' 잡고 반품하십시오 빼냅니다 숫자만 구체화하십시오.
해설 (2)

'' 정수 '' 방법을 사용할 수 있는 방법은 많이 간단해진다는 디코딩합니다 예를 들어:

int helloInt = Integer.decode(hello);
해설 (0)

코틀린

구문 분석 방법을 사용할 수 있는데 그 확장명은 쉽게 다른 프리미티브 유형.

  • [',' (), 네스토린트 &quot 10&quot] [6]
  • [',' (), 네스토롱 &quot 10&quot] [7]
  • [',' (), 네스토부린 &quot true&quot] [1]
  • [',' (), 네스토프로이트 &quot 10.0&quot] [2]
  • [&quot 10.0&quot 네스토둘블 (), ','] [3]
  • [',' (), 네스토비치 &quot 10&quot] [4] [5] - [&quot 10&quot 네스토쇼트 (), ',']

[1]: -string/to-boolean.html https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/kotlin [2]: -string/to-float.html https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/kotlin [3]: -string/to-double.html https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/kotlin [4]: -string/to-byte.html https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/kotlin [5]: -string/to-short.html https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/kotlin [6]: -string/to-int.html https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/kotlin [7]: -string/to-long.html https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/kotlin

Jave

String num = "10";
Integer.parseInt(num );
해설 (0)

5 가지 방법으로 변환할지 첫 번째 방식:

String str = " 123" ;
int i = Integer.parse(str); 
output : 123

두 번째 방법은.

String str = "hello123world";
int i = Integer.parse(str.replaceAll("[\\D]" , "" ) );
output : 123

제 3 의 길:

String str"123";
int i = new Integer(str);
output "123 

네 번째 방식:

String str"123";
int i = Integer.valueOf(Str);
output "123 

다섯 번째 방식:

String str"123";
int i = Integer.decode(str);
output "123 

다른 방법이 있을 수 있습니다. 하지만 이제 s what I remember that& # 39.

해설 (1)