2016-09-10 3 views
1

나는 사용자가 높이를 센티미터와 피트 + 인치로 입력 할 수있는 편집 텍스트를 가지고 있습니다. 5'11 "입니다. 목표 단위에 대한 토글 버튼이 있으므로 사용자가 센티미터를 선택하면 피트 + 인치에서 센티미터로 또는 그 반대로 입력 된 텍스트를 변환해야합니다. 이제 높이를 변환 할 때 센티미터는 끝에 "\" "를 추가합니다. 나는 그것 때문에 횟수가 3높이 변환 - cm에서 피트 및 인치로 (또는 그 반대로)

public void onClick(View view) { 
    switch (view.getId()) 
    { 
     case R.id.btnCm: 
      toggleHeightButton(R.id.btnCm,R.id.btnFeet,false); 
      convertToCentimeter(enter_height); 
      break; 
     case R.id.btnFeet: 
      toggleHeightButton(R.id.btnFeet,R.id.btnCm,true); 
      enter_height.addTextChangedListener(new CustomTextWatcher(enter_height)); 
      break; 
     case R.id.btnKg: 
      toggleweightButton(R.id.btnKg,R.id.btnpound,false); 
      break; 
     case R.id.btnpound: 
      toggleweightButton(R.id.btnpound,R.id.btnKg,true); 
      break; 
    } 
} 

public class CustomTextWatcher implements TextWatcher { 
    private EditText mEditText; 

    public CustomTextWatcher(EditText enter_height) { 
     mEditText = enter_height; 
    } 

    public void beforeTextChanged(CharSequence s, int start, int count, int after) { 
    } 

    public void onTextChanged(CharSequence s, int start, int before, int count) { 
    } 

    public void afterTextChanged(Editable s) { 
     int count = s.length(); 
     String str = s.toString(); 
     if (count == 1) { 
      str = str + "'"; 
     } else if (count == 2) { 
      return; 
     } else if (count == 3) { 
      str = str + "\""; 
     } else if ((count > 4) && (str.charAt(str.length() - 1) != '\"')){ 
      str = str.substring(0, str.length() - 2) + str.charAt(str.length() - 1) + "\""; 
     } else { 
      return; 
     } 

     mEditText.setText(str); 
     mEditText.setSelection(mEditText.getText().length()); 
    } 
} 

답변

1

이 쉽게 정규 표현식을 수행 할 수 있습니다에 도달 할 때 마지막에 "\"를 "추가 내가 넣어 가지고 텍스트 감시자의 생각,하지만 난 당신이 시도해야한다고 생각 먼저 더 간단한 방법.

는 기본적으로, 형식은 xx'xx" 같다. 우리는 ' deliminator를 사용하여 문자열을 split 수 있습니다. 그 방법은, 배열의 첫 번째 항목이 피트의 수입니다.

그런 다음, 우리가 split string 왼쪽의 두 번째 항목은 xx"입니다.이를 위해 우리는 마지막 문자를 제거하기 위해 부분 문자열을 입력하면 인치 수를 얻을 수 있습니다!

직접 코드를 작성해보세요.


당신이 정말로 붙어 경우는, 여기에 솔루션입니다 :

String str = s.toString(); 
String[] splitString = str.split("'"); 
String firstItem = splitString[0]; 
try { 
    int feet = Integer.parseUnsignedInt(firstItem); 
    String secondPart = splitString[1].substring(0, splitString[1].length() - 1); 
    int inches = Integer.parseUnsignedInt(secondPart); 
    // YAY! you got your feet and inches! 
    System.out.println(feet); 
    System.out.println(inches); 
} catch (NumberFormatException e) { 
    return; 
} 

그리고 여기에 솔루션을 사용하는 정규식입니다 :

String str = s.toString(); 
Pattern pattern = Pattern.compile("(\\d+)'((\\d+)\")?"); 
Matcher matcher = pattern.matcher(str); 
if (!matcher.matches()) { 
    return; 
} 

int feet = Integer.parseUnsignedInt(matcher.group(1)); 
String inchesStr = matcher.group(3); 
int inches = 0; 
if (inchesStr != null) { 
    inches = Integer.parseUnsignedInt(inchesStr); 
} 

// YAY! you got your feet and inches! 
3

피트에 센티미터를 관리 할 수있는 수학적 계산이와 그 반대의 변환.

public static String feetToCentimeter(String feet){ 
     double dCentimeter = 0d; 
     if(!TextUtils.isEmpty(feet)){ 
      if(feet.contains("'")){ 
       String tempfeet = feet.substring(0, feet.indexOf("'")); 
       if(!TextUtils.isEmpty(tempfeet)){ 
        dCentimeter += ((Double.valueOf(tempfeet))*30.48); 
       } 
      }if(feet.contains("\"")){ 
       String tempinch = feet.substring(feet.indexOf("'")+1, feet.indexOf("\"")); 
       if(!TextUtils.isEmpty(tempinch)){ 
        dCentimeter += ((Double.valueOf(tempinch))*2.54); 
       } 
      } 
     } 
     return String.valueOf(dCentimeter); 
     //Format to decimal digit as per your requirement 
    } 

    public static String centimeterToFeet(String centemeter) { 
     int feetPart = 0; 
     int inchesPart = 0; 
     if(!TextUtils.isEmpty(centemeter)) { 
      double dCentimeter = Double.valueOf(centemeter); 
      feetPart = (int) Math.floor((dCentimeter/2.54)/12); 
      System.out.println((dCentimeter/2.54) - (feetPart * 12)); 
      inchesPart = (int) Math.ceil((dCentimeter/2.54) - (feetPart * 12)); 
     } 
     return String.format("%d' %d''", feetPart, inchesPart); 
    } 
+0

'dCentimeter' = 91.44, 182.88 등의 경우'centimeterToFeet'가 작동하지 않습니다. –

관련 문제