ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Android] 계산기 만들기
    BACK-END/Android 2020. 11. 12. 12:18

    일단 View 를 만들어놓는다.

    Two.java 소스
    package com.example.lastmycal;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.os.Bundle;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class Two extends AppCompatActivity {
        TextView textView;
        EditText editText;
        String rule=""; //사칙연산기호
        float value1; //값1
        float value2; //값2
        boolean check=false; //기호 연속입력방지 (기호 입력시 true로)
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_two);
    
            textView=findViewById(R.id.view);
            editText=findViewById(R.id.edit);
            editText.setInputType(0); //타자기가 안뜸
        }//end
    
    
        public void num(View vw){
            int id = vw.getId();
            String strtmp = editText.getText().toString();
    
            //if
            if(rule.equals("=") || rule.equals("error")){ //전에 입력한 기호가 등호였거나 에러인경우 초기화
                initialize();
            }
            if(check){
                editText.setText("");
                check=false;
            }
            if(strtmp.startsWith("0") &&! (strtmp.startsWith("0."))){
                editText.setText("");
            }
    
            //switch
            switch(vw.getId()){
                case R.id.allclear:
                    initialize();
                    break;
                case R.id.delete: //입력란 오른쪽부터 하나씩지우기
                    if(!(strtmp.equals(""))) //입력부분이 빈칸이 아닌경우
                        editText.setText(strtmp.substring(0, strtmp.length()-1)); //뒤에서부터 하나씩 지우기
                    if((strtmp.length()==2 && strtmp.startsWith("-")))
                        editText.setText("");
                    break;
    
                    //숫자입력
                case R.id.num0:
                    editText.append("0");
                    break;
                case R.id.num1:
                    editText.append("1");
                    break;
                case R.id.num2:
                    editText.append("2");
                    break;
                case R.id.num3:
                    editText.append("3");
                    break;
                case R.id.num4:
                    editText.append("4");
                    break;
                case R.id.num5:
                    editText.append("5");
                    break;
                case R.id.num6:
                    editText.append("6");
                    break;
                case R.id.num7:
                    editText.append("7");
                    break;
                case R.id.num8:
                    editText.append("8");
                    break;
                case R.id.num9:
                    editText.append("9");
                    break;
                case R.id.point:
                    if(editText.getText().toString().equals("")){ //입력부분이 빈칸인 상태에서 소수점을 입력할경우
                        editText.append("0");
                    } else if(editText.getText().toString().contains(".")){
                        break;
                    }
                        editText.append("."); //소수점 추가
                        break;
                case R.id.whole: //음수/양수 변환
                    if(!editText.getText().toString().equals("")){
                        float numtmp = Float.parseFloat(strtmp);
                        numtmp *= (-1);
                        editText.setText(setNum(numtmp)); //입력부분에 적용
                    }
                    break;
                    }
        }//num end
    
    
    
        public void symbol(View v){ //기호 입력시 실행
            String strtmp = editText.getText().toString(); //입력부분을 문자열로 전환한다
            if(rule.equals("=") || rule.equals("error")){ //전에 입력한 기호가 등호이거나 에러인 경우
                initialize();
            }
            if(!strtmp.equals("")) { //입력 부분이 빈칸이 아닌경우
                if (!check) {
                    float numtmp = Float.parseFloat(strtmp);
                    if (value1 == 0) {
                        value1 = numtmp;
                        editText.setText(setNum(value1));
                    } else {
                        value2 = numtmp;
                        calculate();
                    }
                    textView.append(setNum(numtmp));
                }
    
                switch (v.getId()) {
                    //기호 입력
                    case R.id.divide:
                        if ((Float.parseFloat(strtmp) == 0 && rule.equals("÷"))) { //입력부분의 숫자가 0이고 지금 누른 기호가 나누기인 경우
                            textView.setText("");
                            editText.setText("0을 나눌수는 없습니다.");
                            rule = "error";
                            break;
                        }
                        rule = "÷";
                        break;
                    case R.id.multiply:
                        rule = "×";
                        break;
                    case R.id.minus:
                        rule = "-";
                        break;
                    case R.id.plus:
                        rule = "+";
                        break;
                }
            } else { //빈칸인 경우 메시지 출력
                Toast.makeText(this,"숫자를 입력하세요.", Toast.LENGTH_SHORT).show();
            }
            if(check){
                String tvtmp = textView.getText().toString(); //뷰에 있는 문자열을 받아옴
                tvtmp = tvtmp.substring(0, tvtmp.length()-1);
                textView.setText(tvtmp+rule); //두번째 누른 기호 입력
            } else {
                textView.append(rule);
            }
            check=true; //기호입력체크
        }//end
    
        public void equal(View v){ //등호의 경우
            String strtmp = editText.getText().toString();
            if(!rule.equals("")&&!check){ //입력부분이 빈칸이 아니면서 직전에 기호를 입력하지 않은 경우 check=false
                float numtmp = Float.parseFloat(strtmp); //입력 부분 숫자로 전환
                if(!rule.equals("")){
                    if(rule.equals("÷")&&numtmp ==0){ //직전 기호가 나누기이고 입력 부분이 0인 경우 오류
                        editText.setText("오류");
                        textView.setText("");
                        rule="error";
                        return;
                    }
                    value2=numtmp; //두번째 값에 숫자를 넣음
                    textView.append(setNum(numtmp)+"=");//뷰 부분에 추가
                    calculate(); //계산
                    value1 = 0; //초기화
                    rule="="; //등호 입력 표시
                    check=true; //기호 입력 표시
                }
            }
        } // equal end
    
        private void initialize(){ //초기화 함수
            rule="";
        textView.setText("");
        editText.setText("");
        value1 =0;
        value2 =0;
        check=false;
        }//initialize end
    
        public void calculate(){ //계산함수
            switch(rule){
                case "÷":
                    value1=value1/value2;
                    break;
                case "×":
                    value1=value1*value2;
                    break;
                case "-":
                    value1=value1-value2;
                    break;
                case "+":
                    value1=value1+value2;
                    break;
            }
            editText.setText(setNum(value1));
            value2=0;
        }//end
    
        public String setNum(float num){
            String print;
            if(Float.toString(num).endsWith(".0")) //소숫점아래 숫자가 없는 경우 (문자열이 .0으로 끝나는 경우)
                print=String.valueOf((int)num); //int형으로 문자열 변환
            else //소숫점 아래 숫자가 있는 경우
            print = String.valueOf(num); //float형으로 문자열 변환
            return print; //문자열리턴
        }//end
    }//class END

    댓글

Today
Designed by Danbee Park.