** 사칙연산(Queue단계별로 보기) **

0. 프로젝트명 : QueueCalculatorStep

 

1. 사칙연산을 Queue에 넣다 빼면서 처리

 

2. 화면 설명

    - 4칙 연산식 : +-*/ 연산자가 포함된 계산식

    - queue1 : 4칙 연산식을 queue에 각 문자열별로 넣은 값

    - queue2 : 4칙 연산을 할 때 곱하기, 나누기를 먼저 하고 남은    더하기, 빼기만 남은 연산식

    - pop : 아래 [pop]버튼을 클릭 시 queue에서 빼낸 하나의 문자열

    - 계산     : 곱셈, 나눗셈 하는 식

    - pop버튼 : queue에서 하나를빼내서 보여줌.

 

3. 소스

    https://github.com/farmerkyh/QueueCalculatorStep

 

4. 화면

   

 

 

4. 버전

    - 안드로이드 스튜디오 : v2.2.3

    - Minimum SDK : API 19:Android 4.4 (Kitkat)

5. 소스목록

    1. MainActivity.java

    2. activity_main.xml

 

6. 소스

 

  1. MainActivity.java

 

 package com.example.farmer.queuecalculatorstep;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.Queue;

public class MainActivity extends AppCompatActivity {
    Queue<String> firstQueue = new LinkedList();
    Queue<String> secondQueue = new LinkedList();

    TextView tv_queue1;
    TextView tv_queue2;
    TextView tv_pop1;
    TextView tv_pop2;
    TextView tv_onecalulator;
    TextView tv_result;

    int stepIdx = -1;
    int seq = 0;
    String sResult;

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

        //public member 생성
        tv_queue1 = (TextView)findViewById(R.id.tv_queue1);
        tv_queue2 = (TextView)findViewById(R.id.tv_queue2);
        tv_pop1 = (TextView)findViewById(R.id.tv_pop1);
        tv_pop2 = (TextView)findViewById(R.id.tv_pop2);
        tv_onecalulator = (TextView)findViewById(R.id.tv_onecalulator);
        tv_result = (TextView)findViewById(R.id.tv_result);

        //Button Listener 연동
        Button btnStep  = (Button)findViewById(R.id.btnStep);
        Button btnClear = (Button)findViewById(R.id.btnClear);
        btnStep.setOnClickListener(calOnclickListener);
        btnClear.setOnClickListener(clearOnclickListener);
    }

    Button.OnClickListener calOnclickListener = new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            stepIdx++;
            seq = 0;
            calculatorMain();

            //tv_result.setText(sResult);
        }
    };

    //------------------------------------------------------------------------
    // 사칙연사 시작
    //------------------------------------------------------------------------
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public void calculatorMain(){
        firstQueue.clear();
        secondQueue.clear();

        //1. 산술식을 queue에 넣기
        stringParsing();
        tv_queue1.setText(firstQueue.toString());
        if (stepIdx==0) return//step 1

        //2. Queue에 저장 된 값 중  곱셈. 나눗셈 계산
        multiplyDivideCal();

        //3 Queue에 저장 된 값 중  덧셈. 뺄샘 계산
        sResult = addSubtractCal();
        //System.out.println("괄호 최종결과 => " + sResult);
    }

    //------------------------------------------------------------------------
    // 1차. 문자열 Parsing
    //------------------------------------------------------------------------
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Queue stringParsing(){
        String sNumList = ((EditText)findViewById(R.id.et_arithmetic)).getText().toString();
        String sOneNum = ""//하나의 숫자열
        for(int i=0; i<sNumList.length(); i++){
            String oneChar = sNumList.substring(i, i+1);
            if ("+-*/()".indexOf(oneChar) >= 0 ){

                // 3+(3  과 같이   4칙연산자와 괄호가 동시에 존재 하는 경우 때문
                if (!"".equals(sOneNum)) firstQueue.offer(sOneNum);   
                firstQueue.offer(oneChar);
                sOneNum = "";
            }else{
                sOneNum += oneChar;

                if (i+1 == sNumList.length()){
                    firstQueue.offer(sOneNum);
                }
            }
        }
        return firstQueue;
    }

    //------------------------------------------------------------------------
    // 곱셈, 나눗셈 계산
    //------------------------------------------------------------------------
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Queue multiplyDivideCal(){
        String oneChar;
        String sNum1 = "", sNum2 = "", sResult = "";
        String operator = "";
        BigDecimal nResult = new BigDecimal("0");
        while(firstQueue.peek() != null){
            oneChar  = firstQueue.poll().toString();
            seq++;
            if (stepIdx == seq) tv_queue1.setText(firstQueue.toString());  //step
            if (stepIdx == seq) tv_pop1.setText(oneChar);  //step
            if (stepIdx == seq) tv_pop2.setText("");

            if ("+-".indexOf(oneChar) >= 0 ){
                secondQueue.offer(sNum1);
                secondQueue.offer(oneChar);
                sNum1 = "";
            }else if ("*/".indexOf(oneChar) >= 0 ) {
                operator = oneChar;
            }else{
                if ("".equals(sNum1)){
                    sNum1 = oneChar;
                }else if ("".equals(sNum2)) {
                    sNum2 = oneChar;
                    if ("*".equals(operator)) {
                        nResult = (new BigDecimal(sNum1)).multiply(new BigDecimal(sNum2));
                    }else if ("/".equals(operator)) {
                        nResult = (new BigDecimal(sNum1)).divide(new BigDecimal(sNum2), 0, BigDecimal.ROUND_UP);
                    }

                    if (stepIdx == seq) tv_pop2.setText(sNum1 + " " + operator + " " + sNum2);
                    sResult  = String.valueOf(nResult);

                    sNum1    = sResult;
                    sNum2    = "";
                    operator = "";
                }
            }

            if (firstQueue.peek() == null) secondQueue.offer(sNum1);

            if (stepIdx == seq) tv_queue2.setText(secondQueue.toString());  //step
        }
        return secondQueue;
    }

    //------------------------------------------------------------------------
    // 덧셈. 뺄샘 계산
    //------------------------------------------------------------------------
    @SuppressWarnings({ "rawtypes" })
    public String addSubtractCal(){
        String operator = "";
        String oneChar  = "";
        //if (secondQueue.peek() == null) return "";
        //System.out.println("secondQueue.poll().toString()=" + secondQueue.toString());
        BigDecimal nResult  = new BigDecimal(secondQueue.poll().toString());
        seq++;
        if (stepIdx == seq) tv_queue2.setText(secondQueue.toString());  //step
        if (stepIdx == seq) tv_pop1.setText(nResult.toString());  //step
        if (stepIdx == seq) tv_pop2.setText("");

        while(secondQueue.peek() != null){
            oneChar  = secondQueue.poll().toString();
            seq++;
            if (stepIdx == seq) tv_queue2.setText(secondQueue.toString());  //step
            if (stepIdx == seq) tv_pop1.setText(oneChar);  //step
            if (stepIdx == seq) tv_pop2.setText("");

            if ("+-".indexOf(oneChar) >= 0 ){
                operator = oneChar;
            }else{
                if (stepIdx == seq) tv_pop2.setText(nResult + " " + operator + " " + oneChar);
                if ("+".equals(operator)){
                    nResult = nResult.add(new BigDecimal(oneChar));
                }else if ("-".equals(operator)){
                    nResult = nResult.subtract(new BigDecimal(oneChar));
                }
                operator = "";
            }
        }
        return nResult.toString();
    }

    Button.OnClickListener clearOnclickListener = new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            stepIdx = -1;
            seq = 0;
            tv_queue1.setText("");
            tv_queue2.setText("");
            tv_pop1.setText("");
            tv_pop2.setText("");
            tv_onecalulator.setText("");
            tv_result.setText("");

            //Toast toast = Toast(getApplicationContext());
            //toast.setText(sResult);
            //toast.setDuration(Toast.LENGTH_LONG);

            Toast toast = Toast.makeText(getApplicationContext(), sResult, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.TOP | Gravity.RIGHT, 0, 0);
            View viewToast = toast.getView();

            //Toast BackgroundColor 변경
            //color표기시 xml에서는 "#ffffff"로 하지만
            //java코드에서는 아래와 같이 rgb로 변환하여 사용해줘야 한다.
            viewToast.setBackgroundColor(Color.rgb(255,0,255));

            //Toast Font Color변경
            TextView tvToast = (TextView)viewToast.findViewById(android.R.id.message);
            tvToast.setTextColor(Color.RED);

            toast.show();

            //Toast.makeText(getApplicationContext(), sResult, Toast.LENGTH_LONG).show();
            tv_result.setText(sResult);
        }
    };
}

 

 

 

  2. activity_main.xml

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"

    android:id="@+id/activity_keypad"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fde002"
    android:orientation="vertical"
    tools:context="com.example.farmer.queuecalculatorstep.MainActivity">>

    <!--  1차 : 산술식 -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#b4b2b7"
        android:layout_weight="1">

        <TextView
            android:id="@+id/tv_num"
            android:padding="10dp"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerInParent="true"
            android:text="4칙 연산식"/>

        <EditText
            android:id="@+id/et_arithmetic"
            android:text="16+12/1-2*2"
            android:layout_marginRight="10dp"
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:paddingLeft="10dp"
            android:background="#ffffff"
            android:layout_centerInParent="true"
            android:layout_toRightOf="@+id/tv_num" />

    </RelativeLayout>

    <!--  2차 : queue1 -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#e9e0f7"
        android:layout_marginTop="5dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/tv_lavel1"
            android:padding="10dp"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerInParent="true"
            android:text="queue 1"/>

        <TextView
            android:id="@+id/tv_queue1"
            android:padding="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_centerInParent="true"
            android:layout_toRightOf="@+id/tv_lavel1"
            android:background="#ffffff"
            android:text="queue 1"/>
    </RelativeLayout>

    <!--  3차 : queue2 -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#e9e0f7"
        android:layout_marginTop="5dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/tv_lavel2"
            android:padding="10dp"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerInParent="true"
            android:text="queue 2"/>

        <TextView
            android:id="@+id/tv_queue2"
            android:padding="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_centerInParent="true"
            android:layout_toRightOf="@+id/tv_lavel2"
            android:background="#ffffff"
            android:text="queue 2"/>
    </RelativeLayout>

    <!--  5차 : pop1 -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#e3ebf4"
        android:layout_marginTop="5dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/tv_poplavel1"
            android:padding="10dp"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerInParent="true"
            android:text="pop"/>

        <TextView
            android:id="@+id/tv_pop1"
            android:padding="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_centerInParent="true"
            android:layout_toRightOf="@+id/tv_poplavel1"
            android:background="#ffffff"
            android:text=""/>
    </RelativeLayout>

    <!--  5차 : pop2 -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#e3ebf4"
        android:layout_marginTop="5dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/tv_poplavel3"
            android:padding="10dp"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerInParent="true"
            android:text="계산"/>

        <TextView
            android:id="@+id/tv_pop2"
            android:padding="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_centerInParent="true"
            android:layout_toRightOf="@+id/tv_poplavel3"
            android:background="#ffffff"
            android:text=""/>
    </RelativeLayout>

    <!--  6차 : 4칙연산 하나 계산 -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#dbdee1"
        android:layout_marginTop="5dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/tv_onelavel"
            android:padding="10dp"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerInParent="true"
            android:text="4칙연산"/>

        <TextView
            android:id="@+id/tv_onecalulator"
            android:padding="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_centerInParent="true"
            android:layout_toRightOf="@+id/tv_onelavel"
            android:background="#ffffff"
            android:text=""/>
    </RelativeLayout>

    <!--  7차 : 최종 계산 -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#dbdee1"
        android:layout_marginTop="5dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/tv_resultlabel"
            android:padding="10dp"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerInParent="true"
            android:text="결과"/>

        <TextView
            android:id="@+id/tv_result"
            android:padding="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_centerInParent="true"
            android:layout_toRightOf="@+id/tv_resultlabel"
            android:background="#ffffff"
            android:text=""/>
    </RelativeLayout>

    <!--  8차 : step -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#dbdee1"
        android:layout_marginTop="5dp"
        android:layout_weight="1">

        <Button
            android:id="@+id/btnStep"
            android:text="POP"
            android:layout_centerHorizontal="true"
            android:layout_width="wrap_content"
            android:paddingRight="20dp"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btnClear"
            android:text="Clear"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/btnStep" />
    </RelativeLayout>

    <!--   9차 : 빈공백 -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#ffffff"
        android:layout_weight="0.5">
    </RelativeLayout>
</LinearLayout>

 

 

 

Posted by 농부지기
,

** 위젯 Border 입히기 **

 

 

1. 정의

    - 위젯(Layout, TextView, EditBox ...)들에게 Border를 줄 수 있다.

    - Border를 줄때 테두리뿐만 아니라  backgounrd, margin등을 설정할 수 있다.

 

2. 개발방법

    2.1 res/drawable/border.xml 파일 생성

    2.2 activity_main.xml 파일에서 border를 입히고 싶은 위젯에 

         [android:background="@drawable/border_calbutton"]설정하면 됨


3. res/drawable/border.xml 파일

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 설정된 위젯의 background를 설정
1. 아래 body설정 부분에서 전체영역이 설정 되면 이 background는 아무 표시가 안난다.
2. 아래 body설정 부분에서 top, bottom에 2dp씩 설정 되었기에
이 2dp만큼 아래 부분에 설정된 모양(oval)과 색깔(#6a00ff)이 보인다.
-->
<item>
<shape android:shape="oval">
<solid android:color="#6a00ff" />
</shape>
</item>

<!-- 설정된 위젯의 Body를 설정
1. top, bottom 에 2dp 설정
2. shape : body를 사각형으로 설정
3. color : body에 color지정
-->
<item android:top="2dp" android:bottom="2dp">
<shape android:shape="rectangle">
<solid android:color="#eeffffff" />
</shape>
</item>
</layer-list>

 4. activity_main.xml 파일에서 background를 이용해서 설정

     - RelativeLayout에서도 설정할 수 도있고,  button에도 설정할 수 있다.

 <RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="@drawable/border"
android:layout_weight="1">

<Button
android:id="@+id/bt_clear"
android:text="농부지기"
android:layout_marginLeft="30dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:background="@drawable/border"/>


</RelativeLayout>
Posted by 농부지기
,

** Java에서 TableType으로 Procedure 호출 2 **



1. 테이블

CREATE TYPE [dbo].[INITVALS_MSG] AS TABLE(
    [SDate] [decimal](8, 0) NOT NULL,
    [EDate] [decimal](8, 0) NOT NULL,
    [PlantCode] [nvarchar](10) NOT NULL,
    [LoadType] [nchar](8) NOT NULL,
    [Asset] [bigint] NOT NULL
)



2. Procedure

ALTER PROCEDURE [dbo].[RegisterInitAssets]
    @initmsg INITVALS_MSG ReadOnly
AS
BEGIN
    ...


3. java단에서 호출 예제1

   3.1 vo

public class DBInitialAsset {
    private Integer sDate;
    private Integer eDate;
    private String plantCode;
    private String loadType;
    private Integer asset;

    public DBInitialAsset() {

    }
        ...
}

   3.2 sql procedure 호출 예제1

SQLServerDataTable sourceDataTable = new SQLServerDataTable();   
sourceDataTable.addColumnMetadata("SDate", java.sql.Types.DECIMAL);
sourceDataTable.addColumnMetadata("EDate", java.sql.Types.DECIMAL);
sourceDataTable.addColumnMetadata("PlantCode", java.sql.Types.NVARCHAR);
sourceDataTable.addColumnMetadata("LoadType", java.sql.Types.NCHAR);
sourceDataTable.addColumnMetadata("Asset", java.sql.Types.BIGINT);

// sample data
sourceDataTable.addRow(123, 234, "Plant1", "Type1", 123234);   
sourceDataTable.addRow(456, 789, "Plant2", "Type2", 456789);   

try (CallableStatement cs = conn.prepareCall("{CALL dbo.RegisterInitAssets (?)}")) {
    ((SQLServerCallableStatement) cs).setStructured(1, "dbo.INITVALS_MSG", sourceDataTable);
    boolean resultSetReturned = cs.execute();
    if (resultSetReturned) {
        try (ResultSet rs = cs.getResultSet()) {
            rs.next();
            System.out.println(rs.getInt(1));
        }
    }
}


   3.2 sql procedure 호출 예제2

connection = dataSource.getConnection();
CallableStatement statement = connection.prepareCall("{? = call dbo.RegisterInitAssets(?)}");
statement.registerOutParameter(1, OracleTypes.CURSOR);//you can skip this if procedure won't return anything
statement.setObject(2, new InitvalsMsg()); //I hope you some kind of representation of this table in your project
statement.execute();

ResultSet set = (ResultSet) statement.getObject(1);//skip it too if its not returning anything


'(DB) MS SQL > Procedure (단계별스터디)' 카테고리의 다른 글

MS SQL.PLSQL - 문법  (0) 2017.01.27
MS SQL.PLSQL - 단점  (0) 2017.01.27
MS SQL.PLSQL - 장점  (0) 2017.01.27
MS SQL.PLSQL - 특징  (0) 2017.01.27
Java에서 TableType으로 Procedure 호출 1  (0) 2017.01.06
Posted by 농부지기
,

* Java에서 TableType으로 Procedure 호출 *


- Procedure

CREATE PROCEDURE [dbo].[table_sel]
@tbl INT32Table READONLY
AS
BEGIN
SET NOCOUNT ON;
SELECT value FROM @tbl
END


-아래는 호출이 안되는 script

SqlConnection sqlconn;
System.Data.DataTable tbl = new System.Data.DataTable("INT32Table", "dbo");
tbl.Columns.Add("value", typeof(int));
tbl.Rows.Add(2);
tbl.Rows.Add(3);
tbl.Rows.Add(5);
tbl.Rows.Add(7);
tbl.Rows.Add(11);
using (SqlCommand command = new SqlCommand("table_sel"))
{
    command.Connection = sqlconn;
    command.Parameters.AddWithValue("@tbl", tbl);
    command.CommandType = System.Data.CommandType.StoredProcedure;
    SqlDataReader reader = command.ExecuteReader();

    //do stuff
}


-아래는 될거 같은 script 1

java.sql.connection connection = //driver, url, database, credentials ...

try
{
    PreparedStatement ps =
        connection.prepareStatement("insert into tbl values (?)");
    ps.setInt(1, your 1st int);
    ps.addBatch();
    ps.setInt(1, your 2nd int);
    ps.addBatch();
    ps.setInt(1, your 3rd int);
    ps.addBatch();
    ps.executeBatch();
}
catch (SQLException e)
{
    // err handling goes here
}
finally
{
    // close your resources
}



-아래는 될거 같은 script 2

java.sql.connection connection = //driver, url, database, credentials ...

try
{
    CallableStatement cs =
        connection.prepareCall("{ call table_sel(?) }");
    cs.setInt(1, your int);
    cs.execute();
}
catch (SQLException e)
{
    // err handling goes here
}
finally
{
    // close your ressources
}


'(DB) MS SQL > Procedure (단계별스터디)' 카테고리의 다른 글

MS SQL.PLSQL - 문법  (0) 2017.01.27
MS SQL.PLSQL - 단점  (0) 2017.01.27
MS SQL.PLSQL - 장점  (0) 2017.01.27
MS SQL.PLSQL - 특징  (0) 2017.01.27
Java에서 TableType으로 Procedure 호출 2  (0) 2017.01.06
Posted by 농부지기
,

Gradle을 위한 기본 Groovy 문법


http://blog-joowon.tistory.com/1

http://blog-joowon.tistory.com/2

http://blog-joowon.tistory.com/3

http://blog-joowon.tistory.com/4

http://blog-joowon.tistory.com/5

http://blog-joowon.tistory.com/6

http://blog-joowon.tistory.com/7

Posted by 농부지기
,

* 키보드 보이게 하기

 

   - 한글, 숫자 키보디 임

1. Java단에서 아래 두 줄 추가
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

 

'[Android] - 위젯 > EditText' 카테고리의 다른 글

Android.editText 하단라인 보이기.안보이게 하기  (0) 2017.01.30
Focus 막기. Editting 안되게 하기  (0) 2017.01.02
포커스 주기  (0) 2017.01.02
숫자 관련  (0) 2017.01.01
Posted by 농부지기
,

* marquee  (글씨 흐르기)

 

1. Layout 에서

    <TextView
        android:id="@+id/tv_mqrquee"
        android:text="농부 글씨 흐리기..예전에는 logic으로했는데... "


        android:ellipsize="marquee"
        android:focusable="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:singleLine="true"/>

 

2. 위 Layout과 추가적으로 Java단에서  아래를 해줘야 됨
      ((TextView)findViewById(R.id.tv_mqrquee)).setSelected(true);



Posted by 농부지기
,

* Focus 막기. Editting 안되게 하기

 

1. java단에서 - 첫번째 방법

    editText_name.setFocusableInTouchMode(false);  //결과 box에 edit막기

 

 

2. java단에서 - 두번째 방법

                     - key를 눌러도 EditText 에 값이 안찍힘

                     - 단점 : 하지만 keypad가 보임

    editText_name.setKeyListener(null); 

 

 

'[Android] - 위젯 > EditText' 카테고리의 다른 글

Android.editText 하단라인 보이기.안보이게 하기  (0) 2017.01.30
키보드 보이게 하기  (0) 2017.01.02
포커스 주기  (0) 2017.01.02
숫자 관련  (0) 2017.01.01
Posted by 농부지기
,

* EditText 에 Focus(cursor)주기

 

1. Java단에서

    editText_Name.requestFocus();

 

 

'[Android] - 위젯 > EditText' 카테고리의 다른 글

Android.editText 하단라인 보이기.안보이게 하기  (0) 2017.01.30
키보드 보이게 하기  (0) 2017.01.02
Focus 막기. Editting 안되게 하기  (0) 2017.01.02
숫자 관련  (0) 2017.01.01
Posted by 농부지기
,

** 사칙 연산 알고리즘 **


** 순수 농부 Logic **

1. Queue를 이용해서 개발

2. Double     형으로 계산(괄호 없는 계산식)

   BigDecimal형으로 계산(괄호 없는 계산식)

3. 괄호 존재 하는 사칙연산 계산


------------------------------------------------------


package hanjul.app.sample;


import java.math.BigDecimal;

import java.util.LinkedList;

import java.util.Queue;


public class Calculator01 {


    /**

     * @param args

     */

    public static void main(String[] args) throws Exception{

        // 안디에서 추가할 내용

        //1. 숫자 다음에 (  여는 괄호는 올 수 없음

        //2. ) 닫는 괄호 다음에 숫자또는 소수점이 올 수 없음

        //3. .(소수점)찍을 때 앞에 숫자가 존재 해야 됨

        //4. 사칙연산자 다음에  사칙연산자 또는 ) 닫는 괄호   올 수 없음

        

        //괄호 없는 계산식

        //String sNumList = "11+3*5*5-7/3*12";

        //String sNumList = "11*3*5*5/7/3*12";

        String sNumList = "10/3/4*3";

        doubleCal(sNumList);

        bigDecimalCal(sNumList);

        

        //괄호 존재하는 계산식

        //sNumList = "10/(3/4+(4+3+(5/3+3)))+3";

        sNumList = "0.+(3/4+(4+3+(5/1+3)))+3*(3-4+(4.4-8.8*30))";

        System.out.println("계산식  => " + sNumList);

        BracketCalMain(sNumList);

    }

    

    

    //------------------------------------------------------------------------

    // 괄호 까지 존재하는 사칙연사

    //------------------------------------------------------------------------

    @SuppressWarnings({ "rawtypes", "unchecked" })

    public static void BracketCalMain(String sNumList) throws Exception{

        //0. ( ) 괄호 갯수 검증

        if (checkBracket(sNumList) == false) return;

        

        // 1. 1차 문자열 Parsing

        Queue firstQueue = new LinkedList();

        firstQueue = stringParsing(sNumList);

        System.out.println("----------------------------------------------");

        System.out.println("괄호 1차  => " + firstQueue.toString());

        

        // 2. 2차 괄호안 계산

        Queue secondQueue = new LinkedList();

        String oneChar;

        while(firstQueue.peek() != null){

            oneChar  = firstQueue.poll().toString();

            //System.out.println("괄호  => " + oneChar);

            

            if ("()".indexOf(oneChar) >= 0){

                //괄호안 계산 (firstQueue)

                secondQueue.offer(braketInCal(firstQueue));

            }else{

                secondQueue.offer(oneChar);

            }

        }

        

        //3. Queue에 저장 된 값 중  곱셈. 나눗셈 계산

        secondQueue = multiplyDivideCal(secondQueue);

        

        //4. Queue에 저장 된 값 중  덧셈. 뺄샘 계산

        String sResult = addSubtractCal(secondQueue);

        System.out.println("괄호 최종결과 => " + sResult);

    }

    

    //( ) 괄호 갯수 검증

    public static boolean checkBracket(String sNumList){

        int count1=0, count2=0;

        for(int i=0; i<sNumList.length(); i++){

            if ("(".equals(sNumList.substring(i, i+1))){

                count1 ++;

            }else if (")".equals(sNumList.substring(i, i+1))){

                count2 ++;

            }

        }

        

        if (count1 == count2)

            return true;

        else{

            System.out.println("괄호 () 갯수가 Match되지 않습니다.");

            return false;

        }

    }

    

    //------------------------------------------------------------------------

    // 1차. 문자열 Parsing

    //------------------------------------------------------------------------

    @SuppressWarnings({ "rawtypes", "unchecked" })

    public static Queue stringParsing(String sNumList){

        String sOneNum = "";  //하나의 숫자열

        Queue firstQueue = new LinkedList();

        for(int i=0; i<sNumList.length(); i++){

            String oneChar = sNumList.substring(i, i+1);

            if ("+-*/()".indexOf(oneChar) >= 0 ){

                if (!"".equals(sOneNum)) firstQueue.offer(sOneNum);   // 3+(3  과 같이   4칙연산자와 괄호가 동시에 존재 하는 경우 때문

                firstQueue.offer(oneChar);

                sOneNum = "";   

            }else{

                sOneNum += oneChar;

                

                if (i+1 == sNumList.length()){

                    firstQueue.offer(sOneNum);

                }               

            }                

        }

        return firstQueue;

    }    

    

    //------------------------------------------------------------------------

    // 2차. 괄호 내부 계산 (재귀적 호출)

    //------------------------------------------------------------------------

    @SuppressWarnings({ "unchecked", "rawtypes" })

    public static String braketInCal(Queue firstQueue) throws Exception{

        String oneChar;

        //1. 괄호 내부에 존재 하는 값을 Queue에 저장

        Queue secondQueue = new LinkedList();

        while(firstQueue.peek() != null){

            oneChar  = firstQueue.poll().toString();

            if ("(".equals(oneChar)){

                //괄호안 계산 (firstQueue)

                secondQueue.offer(braketInCal(firstQueue));

            }else if (")".equals(oneChar)){

                break; //닫기 괄호가 나오면 stop

            }else{

                secondQueue.offer(oneChar);

            }

        }

        System.out.println("괄호 2차  => " + secondQueue.toString());

        

        //2. Queue에 저장 된 값 중  곱셈. 나눗셈 계산

        secondQueue = multiplyDivideCal(secondQueue);

        

        //3. Queue에 저장 된 값 중  덧셈. 뺄샘 계산

        String sResult = addSubtractCal(secondQueue);

        

        return sResult;

    }


    //------------------------------------------------------------------------

    // 곱셈, 나눗셈 계산

    //------------------------------------------------------------------------

    @SuppressWarnings({ "rawtypes", "unchecked" })

    public static Queue multiplyDivideCal(Queue inQueue) throws Exception{

        Queue outQueue = new LinkedList();

        String oneChar;

        String sNum1 = "", sNum2 = "", sResult = "";

        String operator = "";

        BigDecimal nResult = new BigDecimal("0");

        while(inQueue.peek() != null){

            oneChar  = inQueue.poll().toString();

            

            if ("+-".indexOf(oneChar) >= 0 ){

                outQueue.offer(sNum1);

                outQueue.offer(oneChar);

                sNum1 = "";

            }else if ("*/".indexOf(oneChar) >= 0 ) {

                operator = oneChar;                

            }else{

                if ("".equals(sNum1)){

                    sNum1 = oneChar;

                }else if ("".equals(sNum2)) {

                    sNum2 = oneChar;

                    if ("*".equals(operator)) {

                        nResult = (new BigDecimal(sNum1)).multiply(new BigDecimal(sNum2));

                    }else if ("/".equals(operator)) {

                        if ("0".equals(sNum2)){

                            //System.out.println("나눗셈 분모에 0 이 존재 합니다.");

                            throw new Exception("나눗셈 분모에 0 이 존재 합니다.");

                            //return null;

                        }

                        

                        //System.out.println("sNum1=" + sNum1 + " :: sNum2=" + sNum2);

                        nResult = (new BigDecimal(sNum1)).divide(new BigDecimal(sNum2), 6, BigDecimal.ROUND_UP);

                    }

                    sResult  = String.valueOf(nResult);

                    //System.out.println(temp + " => oneChar=" + oneChar + " :: sNum1=" + sNum1 + " :: operator=" + operator + " :: sNum2=" + sNum2 + " :: nResult=" + nResult);

                    

                    sNum1    = sResult;

                    sNum2    = "";

                    operator = "";

                    //sResult  = "";

                }

            }

            

            if (inQueue.peek() == null) outQueue.offer(sNum1);

        }        

        return outQueue;

    }


    //------------------------------------------------------------------------

    // 덧셈. 뺄샘 계산

    //------------------------------------------------------------------------

    @SuppressWarnings({ "rawtypes" })

    public static String addSubtractCal(Queue inQueue){

        String operator = "";

        String oneChar  = "";

        //if (inQueue.peek() == null) return "";

        //System.out.println("inQueue.poll().toString()=" + inQueue.toString());

        BigDecimal nResult  = new BigDecimal(inQueue.poll().toString());

        while(inQueue.peek() != null){

            oneChar  = inQueue.poll().toString();

            

            if ("+-".indexOf(oneChar) >= 0 ){

                operator = oneChar;

            }else{

                if ("+".equals(operator)){

                    nResult = nResult.add(new BigDecimal(oneChar));

                }else if ("-".equals(operator)){

                    nResult = nResult.subtract(new BigDecimal(oneChar));

                }

                operator = "";

            }

            //System.out.println("oneChar=" + oneChar + " :: operator=" + operator + " :: nResult=" + nResult);            

        }        

        return nResult.toString();

    }

    

    


    

    //괄호 없는 Bigdecimal 계산

    @SuppressWarnings({ "rawtypes" })

    public static void bigDecimalCal(String sNumList) throws Exception{

        // 1. 1차 문자열 Parsing

        Queue firstQueue = new LinkedList();

        firstQueue = stringParsing(sNumList);

        System.out.println("----------------------------------------------");

        System.out.println("BigDecimal 1차 => " + firstQueue.toString());

        

        //2. Queue에 저장 된 값 중  곱셈. 나눗셈 계산

        Queue secondQueue = new LinkedList();

        secondQueue = multiplyDivideCal(firstQueue);

        

        //3. Queue에 저장 된 값 중  덧셈. 뺄샘 계산

        String sResult = addSubtractCal(secondQueue);             

        

        System.out.println("BigDecimal 최종결과 => " + sResult);        

    }

    

    // 괄호없는 Double 형식으로 계산

    @SuppressWarnings({ "unchecked", "rawtypes" })

    public static void doubleCal(String sNumList) throws Exception{

        String sOneNum = "";  //하나의 숫자열

        Queue firstQueue = new LinkedList();

        for(int i=0; i<sNumList.length(); i++){

            String oneChar = sNumList.substring(i, i+1);

            if ("+-*/".indexOf(oneChar) >= 0 ){

                firstQueue.offer(sOneNum);

                firstQueue.offer(oneChar);

                sOneNum = "";   

            }else{

                sOneNum += oneChar;                

            }                

            

            if (i+1 == sNumList.length()){

                firstQueue.offer(sOneNum);

            }               

            // Toast.makeText(MainActivity.this, sOneNum, Toast.LENGTH_SHORT).show();            

        }

        System.out.println("----------------------------------------------");

        System.out.println("Double 1차 => " + firstQueue.toString());

        

        /*  */            

        //2. 2차  곱셈, 나눗셈  계산            

        Queue secondQueue = new LinkedList();

        String oneChar;

        String sNum1 = "", sNum2 = "", sResult = "";

        String operator = "";

        Double nResult = 0.0;

        while(firstQueue.peek() != null){

            oneChar  = firstQueue.poll().toString();

            

            if ("+-".indexOf(oneChar) >= 0 ){

                secondQueue.offer(sNum1);

                secondQueue.offer(oneChar);

                sNum1 = "";

            }else if ("*/".indexOf(oneChar) >= 0 ) {

                operator = oneChar;                

            }else{

                if ("".equals(sNum1)){

                    sNum1 = oneChar;

                }else if ("".equals(sNum2)) {

                    sNum2 = oneChar;

                    if ("*".equals(operator)) {

                        nResult = (Double.valueOf(sNum1) * Double.valueOf(sNum2));

                    }else if ("/".equals(operator)) {

                        if ("0".equals(sNum2)){

                            //System.out.println("나눗셈 분모에 0 이 존재 합니다.");

                            throw new Exception("나눗셈 분모에 0 이 존재 합니다.");

                            //return;

                        }

                        nResult = (Double.valueOf(sNum1) / Double.valueOf(sNum2));

                    }

                    sResult  = String.valueOf(nResult);

                    //System.out.println(temp + " => oneChar=" + oneChar + " :: sNum1=" + sNum1 + " :: operator=" + operator + " :: sNum2=" + sNum2 + " :: nResult=" + nResult);

                    

                    sNum1    = sResult;

                    sNum2    = "";

                    operator = "";

                    //sResult  = "";

                }

            }

            

            if (firstQueue.peek() == null) secondQueue.offer(sNum1);

        }

        System.out.println("Double 2차 => " + secondQueue.toString());

        

        //3. 3차  덧셈, 뺄셈  계산

        nResult  = 0.0;

        operator = "";

        nResult  = Double.valueOf(secondQueue.poll().toString());

        while(secondQueue.peek() != null){

            oneChar  = secondQueue.poll().toString();

            

            if ("+-".indexOf(oneChar) >= 0 ){

                operator = oneChar;

            }else{

                if ("+".equals(operator)){

                    nResult = nResult + Double.valueOf(oneChar);

                }else if ("-".equals(operator)){

                    nResult = nResult - Double.valueOf(oneChar);

                }

                operator = "";

            }

            System.out.println("oneChar=" + oneChar + " :: operator=" + operator + " :: nResult=" + nResult);            

        }

        

        System.out.println("Double 최종결과 => " + nResult);        

    }    

}



Posted by 농부지기
,