[국비학원 기록/Android] 간단한 계산기 app 만들기
my code archive
article thumbnail
반응형
  • 안드로이드 간단한 계산기 앱 구현하기

가상 기기는 Pixel 2 API로 추가해주었다.

 

  • 더하기, 빼기, 곱하기, 나누기 기능 구현

🔍activity_main.xml 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/Edit1"
        android:layout_weight="1"
        android:layout_margin="6dp"
        android:hint="숫자1 입력하세요"/>
 
    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/Edit2"
        android:layout_weight="1"
        android:layout_margin="6dp"
        android:hint="숫자2 입력하세요"/>
 
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/BtnAdd"
        android:layout_weight="1"
        android:layout_margin="6dp"
        android:onClick="onClick"
        android:text="더하기"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/BtnSub"
        android:layout_weight="1"
        android:layout_margin="6dp"
        android:onClick="onClick"
        android:text="빼기"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/BtnMul"
        android:layout_weight="1"
        android:layout_margin="6dp"
        android:onClick="onClick"
        android:text="곱하기"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/BtnDiv"
        android:layout_weight="1"
        android:layout_margin="6dp"
        android:onClick="onClick"
        android:text="나누기"/>
 
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/TextResult"
        android:layout_weight="1"
        android:layout_margin="10dp"
        android:text="계산 결과 : "
        android:textColor="#FF0000"
        android:textSize="30dp"/>
</LinearLayout>
cs
  • 나머지 기능 추가
1
2
3
4
5
6
7
8
 <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/BtnMod"
        android:layout_weight="1"
        android:layout_margin="6dp"
        android:onClick="onClick"
        android:text="나머지"/>
cs

 

 
🔍MainActivity 작성
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package kr.co.calculator;
 
import androidx.appcompat.app.AppCompatActivity;
 
import android.os.Bundle;
import android.view.MotionEvent;
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 {
 
    EditText edit1, edit2;
    Button btnAdd, btnSub, btnMul, btnDiv, btnMod;
    TextView textResult;
    String num1, num2;      //입력될 2개 문자열을 저장할 변수
    Double result;          //계산 결과를 저장할 실수 변수
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);         //엑티비티 화면 설정하는 메서드, XML파일과 코드
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setIcon(R.drawable.ic_launcher);
        setTitle("간단한 계산기");
 
        edit1 = findViewById(R.id.Edit1);       //에디트 텍스트를 변수에 대입
        edit2 = findViewById(R.id.Edit2);
 
        btnAdd = findViewById(R.id.BtnAdd);     //버튼을 변수에 대입
        btnSub = findViewById(R.id.BtnSub);
        btnMul = findViewById(R.id.BtnMul);
        btnDiv = findViewById(R.id.BtnDiv);
        btnMod = findViewById(R.id.BtnMod);
 
        textResult = findViewById(R.id.TextResult);     //텍스트뷰를 변수에 대입
 
        //<더하기>버튼 클릭했을 때 동작 => 버튼에 터치 이벤트 리스너 정의
        //=>터치 시에 동작하는 내용을 onTouch() 메서드 안에 코딩함.
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                num1 = edit1.getText().toString();
                num2 = edit2.getText().toString();
 
                //값이 비어있다면
                if (num1.trim().equals(""|| num2.trim().equals("")) {
                    Toast.makeText(getApplicationContext(), "입력값이 비었습니다.", Toast.LENGTH_SHORT).show();
                } else {
                    result = Double.parseDouble(num1) + Double.parseDouble(num2);
                    textResult.setText("계산 결과 :" + result.toString());
                }
            }
        });
 
        btnSub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                num1 = edit1.getText().toString();
                num2 = edit2.getText().toString();
 
                //값이 비어있다면
                if (num1.trim().equals(""|| num2.trim().equals("")) {
                    Toast.makeText(getApplicationContext(), "입력값이 비었습니다.", Toast.LENGTH_SHORT).show();
                } else {
                    result = Double.parseDouble(num1) - Double.parseDouble(num2);
                    textResult.setText("계산 결과 :" + result.toString());
                }
            }
        });
 
        btnMul.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                num1 = edit1.getText().toString();
                num2 = edit2.getText().toString();
 
                //값이 비어있다면
                if (num1.trim().equals(""|| num2.trim().equals("")) {
                    Toast.makeText(getApplicationContext(), "입력값이 비었습니다.", Toast.LENGTH_SHORT).show();
                } else {
                    result = Double.parseDouble(num1) * Double.parseDouble(num2);
                    textResult.setText("계산 결과 :" + result.toString());
                }
            }
        });
cs
  • 입력값이 비었을 때 Toast 메시지 출력 기능 추가
  • 0으로 나누었을 때 메시지 출력 기능 추가
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
 btnDiv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                num1 = edit1.getText().toString();
                num2 = edit2.getText().toString();
 
                //값이 비어있다면
                if (num1.trim().equals(""|| num2.trim().equals("")) {
                    Toast.makeText(getApplicationContext(), "입력값이 비었습니다.", Toast.LENGTH_SHORT).show();
                } else {
                   //num2가 0이면 나누지 않음.
                    if(num2.trim().equals("0")){
                        Toast.makeText(getApplicationContext(), "0으로 나누면 안됩니다.", Toast.LENGTH_SHORT).show();
                    }else{
                        result = Double.parseDouble(num1)/Double.parseDouble(num2);
                        result = (result * 10)/10.0;        //소수점 아래 1자리까지만 출력
                        textResult.setText("계산 결과 : "+result.toString(result));
                    }
                }
            }
        });
 
        btnMod.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                num1 = edit1.getText().toString();
                num2 = edit2.getText().toString();
 
                //값이 비어있다면
                if (num1.trim().equals(""|| num2.trim().equals("")) {
                    Toast.makeText(getApplicationContext(), "입력값이 비었습니다.", Toast.LENGTH_SHORT).show();
                } else {
                    //num2가 0이면 나누지 않음.
                    if(num2.trim().equals("0")){
                        Toast.makeText(getApplicationContext(), "0으로 나누면 안됩니다.", Toast.LENGTH_SHORT).show();
                    }else{
                        result = Double.parseDouble(num1)%Double.parseDouble(num2);
                        result = (result * 10)/10.0;        //소수점 아래 1자리까지만 출력
                        textResult.setText("계산 결과 : "+result.toString(result));
                    }
                }
            }
        });
 
    }
}
cs

 

반응형
profile

my code archive

@얼레벌레 개발자👩‍💻

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

반응형