본문 바로가기
안드로이드 프로그래밍

[안드로이드 프로그래밍] 4장 직접 풀어보기 4-3

by Excellent Summer 2022. 9. 16.

실행 결과 처음 화면

 

[ activity_main.xml ]

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/Edit1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:hint="숫자1" />

    <EditText
        android:id="@+id/Edit2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:hint="숫자2" />

    <Button
        android:id="@+id/BtnAdd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="더하기" />

    <Button
        android:id="@+id/BtnSub"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="빼기" />

    <Button
        android:id="@+id/BtnMul"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="곱하기" />

    <Button
        android:id="@+id/BtnDiv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="나누기" />

    <Button
        android:id="@+id/BtnMod"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="나머지 값" />

    <TextView
        android:id="@+id/TextResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="계산 결과 : "
        android:textColor="#FF0000"
        android:textSize="30dp" />

</LinearLayout>

 

[ MainActivity.java ]

- Toast

  • 구조
    • Toast.makeText(애플리케이션 Context, 사용자에게 표시되어야 하는 텍스트, 토스트 메시지가 화면에 남아 있어야 하는 시간).show();
  • 메서드 설명
    • makeText() 메서드는 올바르게 초기화된 Toast 객체를 반환합니다.
    • 토스트 메시지를 표시하려면 show() 메서드를 호출합니다.

- 형 변환

  • Integer.parseInt()
    • 문자열을 정수형(Int)으로 변환
  • Float.parseFloat()
    • 문자열을 실수형(Float)으로 변환
  • Double.parseDouble()
    • 문자열을 실수형(Double)으로 변환

- 기타

  • edit1.getText().toString().equals("")
    • edit1에 입력한 텍스트를 가져와 String으로 형변환후 ""(아무것도 없는 텍스트)와 같은지 비교하는 코드

- 예상 오류

  • result 변수 형식을 정수형(int)로 하고 실수형으로 계산한 값을 넣을 시 오류 발생
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private EditText edit1, edit2;
    private Button btnAdd, btnSub, btnMul, btnDiv, btnMod;
    private TextView textResult;
    private String num1, num2;
    //    private int result; // 정수로 계산할 때
    private Double result;  // 실수로 계산할 때

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("초간단 계산기 (수정)");

        edit1 = (EditText) findViewById(R.id.Edit1);
        edit2 = (EditText) findViewById(R.id.Edit2);
        btnAdd = (Button) findViewById(R.id.BtnAdd);
        btnSub = (Button) findViewById(R.id.BtnSub);
        btnMul = (Button) findViewById(R.id.BtnMul);
        btnDiv = (Button) findViewById(R.id.BtnDiv);
        btnMod = (Button) findViewById(R.id.BtnMod);

        textResult = (TextView) findViewById(R.id.TextResult);

        // 더하기
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 값을 입력하지 않았을 때 오류 메시지 토스트
                if (edit1.getText().toString().equals("") || edit2.getText().toString().equals("")) {
                    Toast.makeText(MainActivity.this, "숫자를 입력하세요.", Toast.LENGTH_SHORT).show();
                    return;
                }
                num1 = edit1.getText().toString();
                num2 = edit2.getText().toString();
//                result = Integer.parseInt(num1) + Integer.parseInt(num2);   // 정수로 계산할때
                result = Double.parseDouble(num1) + Double.parseDouble(num2);   // 실수로 계산할때
                textResult.setText("계산 결과 : " + result);
            }
        });

        // 빼기
        btnSub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 값을 입력하지 않았을 때 오류 메시지 토스트
                if (edit1.getText().toString().equals("") || edit2.getText().toString().equals("")) {
                    Toast.makeText(MainActivity.this, "숫자를 입력하세요.", Toast.LENGTH_SHORT).show();
                    return;
                }
                num1 = edit1.getText().toString();
                num2 = edit2.getText().toString();
                //                result = Integer.parseInt(num1) - Integer.parseInt(num2);   // 정수로 계산할때
                result = Double.parseDouble(num1) - Double.parseDouble(num2);   // 실수로 계산할때
                textResult.setText("계산 결과 : " + result);
            }
        });

        // 곱셈
        btnMul.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 값을 입력하지 않았을 때 오류 메시지 토스트
                if (edit1.getText().toString().equals("") || edit2.getText().toString().equals("")) {
                    Toast.makeText(MainActivity.this, "숫자를 입력하세요.", Toast.LENGTH_SHORT).show();
                    return;
                }
                num1 = edit1.getText().toString();
                num2 = edit2.getText().toString();
//                result = Integer.parseInt(num1) * Integer.parseInt(num2);   // 정수로 계산할때
                result = Double.parseDouble(num1) * Double.parseDouble(num2);   // 실수로 계산할때
                textResult.setText("계산 결과 : " + result);
            }
        });

        // 나누기
        btnDiv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 값을 입력하지 않았을 때 오류 메시지 토스트
                if (edit1.getText().toString().equals("") || edit2.getText().toString().equals("")) {
                    Toast.makeText(MainActivity.this, "숫자를 입력하세요.", Toast.LENGTH_SHORT).show();
                    return;
                }
                // 0으로 나눌 시 토스트 메세지와 계산 안함
                if (edit2.getText().toString().equals("0")) {
                    Toast.makeText(MainActivity.this, "0으로 나눌 수 없습니다.", Toast.LENGTH_SHORT).show();
                    return;
                }
                num1 = edit1.getText().toString();
                num2 = edit2.getText().toString();
//                result = Integer.parseInt(num1) / Integer.parseInt(num2);   // 정수로 계산할때
                result = Double.parseDouble(num1) / Double.parseDouble(num2);   // 실수로 계산할때
                textResult.setText("계산 결과 : " + result);
            }
        });

        // 나머지
        btnMod.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 값을 입력하지 않았을 때 오류 메시지 토스트
                if (edit1.getText().toString().equals("") || edit2.getText().toString().equals("")) {
                    Toast.makeText(MainActivity.this, "숫자를 입력하세요.", Toast.LENGTH_SHORT).show();
                    return;
                }
                num1 = edit1.getText().toString();
                num2 = edit2.getText().toString();
//                result = Integer.parseInt(num1) % Integer.parseInt(num2);   // 정수로 계산할때
                result = Double.parseDouble(num1) % Double.parseDouble(num2);   // 실수로 계산할때
                textResult.setText("계산 결과 : " + result);
            }
        });
    }
}

*상황에 맞게 주석( // )을 달고 풀고하셔서 결과 도출하시면 됩니다 :)

 

❗ 틀린 내용이나 오류가 있으면 덧글 남겨주시면 감사하겠습니다:) ❗

댓글