마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

안드로이드 질문 합니다.

0 추천
toast 메시지는 뜨긴 합니다만 에뮬이 꺼지는데 이거 어디가 문제인건가요...

btn1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn1)
            cm = edtText1.getText().toString().trim();
        kg = edtText2.getText().toString().trim();

        if (cm.equals("") || kg.equals("")) {
            Toast.makeText(getApplicationContext(), "키와 몸무게를 입력하세요.", Toast.LENGTH_SHORT).show();
    }

        cm = edtText1.getText().toString();
        kg = edtText2.getText().toString();

        result1 = Double.parseDouble(kg) / ((Double.parseDouble(cm) / 100) * (Double.parseDouble(cm) / 100));
        if (result1 < 18.5) {
            result2 = "저체중";
            imageView.setImageResource(R.drawable.ic_baseline_sentiment_dissatisfied_24);
        } else if (result1 >= 18.5 && result1 < 23) {
            result2 = "정상";
            imageView.setImageResource(R.drawable.ic_baseline_sentiment_satisfied_alt_24);
        } else if (result1 >= 23 && result1 < 25) {
            result2 = "과체중";
            imageView.setImageResource(R.drawable.ic_baseline_sentiment_dissatisfied_24);
        } else if (result1 >= 25) {
            result2 = "비만";
            imageView.setImageResource(R.drawable.ic_baseline_sentiment_very_dissatisfied_24);
        }

        String BMI = String.format("%.2f", result1);
        textResult1.setText("남성 BMI : " + BMI + "\n" + result2 + "\n");

    }
});
156343 (120 포인트) 님이 2022년 9월 10일 질문

2개의 답변

0 추천

정확한건 에러 로그를 확인하셔야 할 것 같고, 올리신 코드만 가지고 추측해 볼 때는 String타입을 Double로 변화한 때 Exception이 발생할 가능성이 있어 보입니다. parseDouble같은 메소드는 API문서를 보시면 어떤 Exception이 발생되는지 나오기 때문에 , 이렇게 Exception이 발생할 경우 Exception 처리가 필요한지 확인해 보신다음, 요구사항에 맞게 처리하시는세 좋습니다.

https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html

문서에 따르면 Double.parseDouble 은 NullPointerException과 NumberFormatException이 발생할 수 있다고 되어 있습니다. 그리고 통상 이런 종류의 메소드는 유틸리티 클래스를 만들어 사용하는 것이 자바에서는 일반적입니다. 아래처럼 유틸리티 클래스를 하나 만드시고 이걸 가져다 사용하세요.

public class FormatUtils {
    public static Double toDoubleOrNull(String string) {
        try {
            return Double.parseDouble(string);
        } catch (NullPointerException | NumberFormatException e) {
            return null;
        }
    }
}

 

    @Nullable
    private String getHeight() {
        return edtText1.getText().toString().trim();
    }

    @Nullable
    private String getWeight() {
        return edtText2.getText().toString().trim();
    } btn1.setOnClickListener(new View.OnClickListener()

    {
        @Override public void onClick (View view){
        calculateBMI();
    }
    });

    private void caclulateBMI() {
        String sHeight = getHeight();
        String sWeight = getWeight();
        if ("".equals(sHeight) || "".equals(sWeight)) {
            Toast.makeText(getApplicationContext(), "키와 몸무게를 입력하세요.", Toast.LENGTH_SHORT).show();
            return;
        }
        Double heightInCm = FormatUtils.toDoubleOrNull(sHeight);
        Double weightInKg = FormatUtils.toDoubleOrNull(sWeight);
        if (heightInCm == null || weightInKg == null) {
            Toast.makeText(getApplicationContext(), "키와 몸무게를 올바르게 입력하세요.", Toast.LENGTH_SHORT).show();
            return;
        }
        double bmi = getBMI(heightInCm, weightInKg);
        if (bmi < 18.5) {
            result2 = "저체중";
            imageView.setImageResource(R.drawable.ic_baseline_sentiment_dissatisfied_24);
        } else if (bmi >= 18.5 && bmi < 23) {
            result2 = "정상";
            imageView.setImageResource(R.drawable.ic_baseline_sentiment_satisfied_alt_24);
        } else if (bmi >= 23 && bmi < 25) {
            result2 = "과체중";
            imageView.setImageResource(R.drawable.ic_baseline_sentiment_dissatisfied_24);
        } else if (bmi >= 25) {
            result2 = "비만";
            imageView.setImageResource(R.drawable.ic_baseline_sentiment_very_dissatisfied_24);
        }
        String BMI = String.format("%.2f", result1);
        textResult1.setText("남성 BMI : " + BMI + "\n" + result2 + "\n");
    }

    public double getBMI(double heightInCm, double weightInKg) {
        return weightInKg / (heightInCm / 100) * (heightInCm / 100));
    }



위와 같은 형태로 처리하시고, 여력이 생기시면 BMI를 계산하는 로직을 완전히 분리해서 별도의 클래스로 만드시고 유닛테스트까지 시도해 보세요.
 

public enum BMIType {
    UNKNOWN(0, 0, R.string.error, 0),
    UNDERWEIGHT(0.0, 18.5, R.string.underweight, R.drawable.ic_baseline_sentiment_dissatisfied_24),
    HEALTHY(18.6, 24.9, R.string.healthy, R.drawable.ic_baseline_sentiment_dissatisfied_24),
    OVERWEIGHT(25, 29.9, R.string.overweight, R.drawable.ic_baseline_sentiment_dissatisfied_24),
    OBESE(30, Double.MAX_VALUE, R.string.obese, R.drawable.ic_baseline_sentiment_very_dissatisfied_24);

    private final double from;
    private final double to;
    private final int strId;
    private final int drawableId;

    UiBMIType(double from, double to, int strId, int drawableId) {
        this.from = from;
        this.to = to;
        this.strId = strId;
        this.drawableId = drawableId;
    }

    public double getFrom() {
        return from;
    }

    public double getTo() {
        return to;
    }

    public int getStrId() {
        return strId;
    }

    public int getDrawableId() {
        return drawableId;
    }
}



 

public class BMI {
    private final BMIType type;
    private final double value;

    public static BMI with(double value) {
        BMIType bmiType = BMIType.UNKNOWN;

        for (BMIType type : BMIType.values()) {
            if (value >= type.getFrom() && value <= type.getTo()) {
                bmiType = type;
                break;
            }
        }

        return new BMI(bmiType, value);
    }

    private BMI(BMIType type, double value) {
        this.type = type;
        this.value = value;
    }

    public BMIType getType() {
        return type;
    }

    public double getValue() {
        return value;
    }
}

 

spark (227,830 포인트) 님이 2022년 9월 10일 답변
spark님이 2022년 9월 11일 수정
0 추천

 

public class BMICalculator {
    private static final int MIN_HEIGHT = 91;
    private static final int MAX_HEIGHT = 250;
    private static final int MIN_WEIGHT = 30;
    private static final int MAX_WEIGHT = 250;

    public static BMIResult getBMI(String heightString, String weightString) {
        if ((heightString == null || heightString.trim().isEmpty()) && (weightString == null || weightString.trim().isEmpty())) {
            return BMIResult.error("키와 몸무게를 입력하세요.");
        }

        Double height = FormatUtils.toDoubleOrNull(heightString.trim());
        if (height == null || height < MIN_HEIGHT || height > MAX_HEIGHT) {
            return BMIResult.error(String.format("키는 %d - %d cm 사이로 입력해야 합니다.", MIN_HEIGHT, MAX_HEIGHT));
        }

        Double weight = FormatUtils.toDoubleOrNull(weightString.trim());
        if (weight == null || weight < MIN_WEIGHT || weight > MAX_WEIGHT) {
            return BMIResult.error(String.format("몸무게는 %d = %d kg 사이로 입력해야 합니다.", MIN_WEIGHT, MAX_WEIGHT));
        }

        BMI bmi = getBMI(height, weight);
        return BMIResult.with(bmi);
    }

    public static BMI getBMI(double heightInCm, double weightInKg) {
        double bmi = calculate(heightInCm, weightInKg);
        return BMI.with(bmi);
    }

    private static double calculate(double heightInCm, double weightInKg) {
        final double result = weightInKg / ((heightInCm / 100) * (heightInCm / 100));
        return (Math.round(result * 10) * 1.0) / 10;
    }
}

 

public class BMIActivity extends AppCompatActivity {

    private Button calculateBtn;
    private EditText heightEdt, weightEdt;
    private ImageView bmiImg;
    private TextView bmiTxt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bmi);

        initViews();
    }

    private void initViews() {
        heightEdt = findViewById(R.id.heightEdt);
        weightEdt = findViewById(R.id.weightEdt);
        bmiImg = findViewById(R.id.bmiImg);
        bmiTxt = findViewById(R.id.bmiTxt);
        calculateBtn = findViewById(R.id.calculateBtn);
        calculateBtn.setOnClickListener(v -> {
            calculateBMI();
        });
    }

    private void calculateBMI() {
        BMIResult bmiResult = BMICalculator.getBMI(getHeight(), getWeight());
        if (!bmiResult.isSuccess()) {
            Toast.makeText(this, bmiResult.getMessage(), Toast.LENGTH_SHORT).show();
            return;
        }

        bindBMI(bmiResult.getBmi());
    }

    private void bindBMI(BMI bmi) {
        bmiImg.setImageResource(bmi.getType().getDrawableId());
        bmiTxt.setText(getString(R.string.bm_result, getString(bmi.getType().getStrId()), bmi.getValue()));
    }

    private String getHeight() {
        return heightEdt.getText().toString().trim();
    }

    private String getWeight() {
        return weightEdt.getText().toString().trim();
    }
}

 

 

spark (227,830 포인트) 님이 2022년 9월 10일 답변
spark님이 2022년 9월 11일 수정
...