안녕하세요 지난시간에 이어 계산하는 부분을 추가하는데요.


StringTokenizer 클래스를 사용합니다.


생성을 할때 내용과 딜리미터를 전달합니다.

예를 들어  내용이 A_B_C  딜리미터가 _ 라면 

StringTokenizer st = new StringTokenizer( "A_B_C" , "_" ); 

이렇게 사용하시면 됩니다. 게다가 딜리미터의경우 멀티로도 가능합니다. 

예를들면 StringTokenizer("A+B-C/D", "+-/") 이런 식으로 사용이가능하가는 거지요~

while( st.hasMoreTokens() ) {
          double number = Double.parseDouble(st.nextToken());
          numberList.add( number );
          Log.d("aaa", String.valueOf(number) );
}



계산기의 기본 아이디어를 설명드리겠습니다.


StringTokenizer로 숫자부분은 얻을수있습니다. 하지만  Operator( +-/* )는 얻을수가 없어요

그래서 숫자, 오퍼레이터는 내용에 추가합니다.


사용자가 1+1/10 이런식으로 입력했다면 TextView에 계속해서 추가해줍니다.

사용자가 오퍼레이터 입력시 operatorList 변수를 만들어 해당 operator를 저장시킵니다.


그리고 계산을 누르게되면 TextView 내용에대해 StringTokenizer를 이용하여 숫자부분만 뽑아냅니다.

그리고 Operator같은 경우는 정상적인 경우라면


만약 사용자가 10+20/30 을 입력했다면 OperatorList 와 NumberList는 아래와 같습니다.

OperatorList는 사용자가 기호를 입력할때마다 add 시켜주면 저렇게 입력이되구요

+입력될때 operatorList 에 입력 / 입력될때 입력이 됩니다.

NumberList는 StringTokenizer 를 이용하여 nextToken으로 값을 뽑아내면 아래와같이 입력됩니다.

 

사용자입력

10

+

20

/

30

OperatorList

0

1

 

 

 

+

/

 

 

 

NumberList

0

1

2

 

 

 

10

20

30

 

 

         








가. NumberList[0], NumberList[1] 에대해 OperatorList[0]계산 -> 10 , 20 에 대한 + 계산  => 30 

나. 가.의 결과 , NumberList[2] 에 대해 OperatorList[1]계산 -> 30 , 30 에 대한 / 계산 => 1

의 형식으로 됩니다.


아래는 Calc 함수내용입니다.


private String calc(String exp) {
		
		
		ArrayList<Double> numberList = new ArrayList<Double>();
		StringTokenizer st = new StringTokenizer(exp,"X/+-");
		
		
		while( st.hasMoreTokens() ) {
			double number = Double.parseDouble(st.nextToken());
			numberList.add( number );
			Log.d("aaa", String.valueOf(number) );
		}
		
		double result = numberList.get(0);
		Log.d("aaa", String.valueOf(result) );
		for( int i = 0 ; i < operatorList.size() ; i++ ) {
			String operator = operatorList.get(i);
			
			if( "*".equals(operator)){
				result = ( result * numberList.get(i+1));
			}else if( "/".equals(operator)){
				result = ( result / numberList.get(i+1));
			}else if( "+".equals(operator)){
				result = ( result + numberList.get(i+1));
			}else if( "-".equals(operator)){
				result = ( result - numberList.get(i+1));
			}
		}
		operatorList.clear();
		numberList.clear();
		
		return String.valueOf(result);
	}



ShinExample_05.zip


Posted by App.SHIN
:

오늘은 계산기를 만들어보겠습니다.

이전에 배운내용 처럼 

LinearLayout android:orientation="vertical" 옵션과 android:layout_weight 옵션을 사용 하여 화면을 굿헝합니다.

android_weight 는 비율로 생각하시면 됩니다.

4:1:1:1

<LinearLayout  세로 >

<LinearLayout 가로 > 가로 가로 가로 ... <LinearLayout >

<LinearLayout 가로 > 가로 가로 가로 ... <LinearLayout >

<LinearLayout 가로 > 가로 가로 가로 ... <LinearLayout >

...

</LinearLayout >


이런식으로 구성합니다.


res/layout/activity_calculator.xml


<!--?xml version="1.0" encoding="utf-8"?-->
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">
    <LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <LinearLayout 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="3">
    <TextView
        android:id="@+id/text_result"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="right"
    android:textSize="30dip" >
    </TextView>
    </LinearLayout>
    <LinearLayout 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_weight="1">
     <Button
        android:id="@+id/button_back"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="←" 
        android:layout_weight="1"/>
      <Button
        android:id="@+id/button_clear"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="C" 
        android:layout_weight="1"/>
       <Button
        android:id="@+id/button_equal"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="=" 
        android:layout_weight="1"/>
       <Button
        android:id="@+id/button_plus"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="+" 
        android:layout_weight="1"/> 
    </LinearLayout>
    <LinearLayout 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_weight="1">
     <Button
        android:id="@+id/button_7"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="7"
        android:layout_weight="1" />
      <Button
        android:id="@+id/button_8"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="8" 
        android:layout_weight="1"/>
       <Button
        android:id="@+id/button_9"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="9"
        android:layout_weight="1" />
       <Button
        android:id="@+id/button_minus"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="-"
        android:layout_weight="1" />
    </LinearLayout>
    <LinearLayout 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_weight="1">
     <Button
        android:id="@+id/button_4"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="4"
        android:layout_weight="1" />
      <Button
        android:id="@+id/button_5"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="5" 
        android:layout_weight="1"/>
       <Button
        android:id="@+id/button_6"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="6"
        android:layout_weight="1" />
       <Button
        android:id="@+id/button_multi"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="*"
        android:layout_weight="1" />
    </LinearLayout>
    <LinearLayout 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_weight="1">
       <Button
        android:id="@+id/button_1"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="1" 
        android:layout_weight="1"/>
      <Button
        android:id="@+id/button_2"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="2" 
        android:layout_weight="1"/>
       <Button
        android:id="@+id/button_3"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="3" 
        android:layout_weight="1"/>
     
       <Button
        android:id="@+id/button_devide"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="/" 
        android:layout_weight="1"/>
    </LinearLayout>
</LinearLayout>


Layout_weight 를 사용할때 android:layout_height="wrap_content"를 사용해주세요

결과




public class CalculatorActivity extends Activity implements OnClickListener {
	private Button b1;
	private Button b2;
	private Button b3;
	private Button b4;
	private Button b5;
	private Button b6;
	private Button b7;
	private Button b8;
	private Button b9;
	private Button b_claer;
	private Button b_back;
	private Button b_devide;
	private Button b_plus;
	private Button b_minus;
	private Button b_multi;
	private Button b_equal;
	
	private TextView result;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_calculator );	

		b1 = (Button) findViewById( R.id.button_1 );
		b1.setOnClickListener(this);
		b2 = (Button) findViewById( R.id.button_2 );
		b2.setOnClickListener(this);
		b3 = (Button) findViewById( R.id.button_3 );
		b3.setOnClickListener(this);
		b4 = (Button) findViewById( R.id.button_4 );
		b4.setOnClickListener(this);
		b5 = (Button) findViewById( R.id.button_5 );
		b5.setOnClickListener(this);
		b6 = (Button) findViewById( R.id.button_6 );
		b6.setOnClickListener(this);
		b7 = (Button) findViewById( R.id.button_7 );
		b7.setOnClickListener(this);
		b8 = (Button) findViewById( R.id.button_8 );
		b8.setOnClickListener(this);
		b9 = (Button) findViewById( R.id.button_9 );
		b9.setOnClickListener(this);
		b_claer = (Button) findViewById( R.id.button_clear );
		b_claer.setOnClickListener(this);
		b_back = (Button) findViewById( R.id.button_back );
		b_back.setOnClickListener(this);
		b_devide = (Button) findViewById( R.id.button_devide );
		b_devide.setOnClickListener(this);
		b_plus = (Button) findViewById( R.id.button_plus );
		b_plus.setOnClickListener(this);
		b_minus = (Button) findViewById( R.id.button_minus );
		b_minus.setOnClickListener(this);
		b_multi = (Button) findViewById( R.id.button_multi );
		b_multi.setOnClickListener(this);
		b_equal = (Button) findViewById( R.id.button_equal );
		b_equal.setOnClickListener(this);
		result = (TextView) findViewById( R.id.text_result );
	}

	@Override
	public void onClick(View v) {
		if( v.equals( b1 )){
			if( result.getText().length() == 1 && "0".equals(result.getText())){
				result.setText("1");
			}else {
				result.setText( result.getText()+"1");
			}
		}else if( v.equals( b2 )){
			if( result.getText().length() == 1 && "0".equals(result.getText())){
				result.setText("2");
			}else {
				result.setText( result.getText()+"2");
			}
		}else if( v.equals( b3 )){
			if( result.getText().length() == 1 && "0".equals(result.getText())){
				result.setText("3");
			}else {
				result.setText( result.getText()+"3");
			}
		}else if( v.equals( b4 )){
			if( result.getText().length() == 1 && "0".equals(result.getText())){
				result.setText("4");
			}else {
				result.setText( result.getText()+"4");
			}
		}else if( v.equals( b5 )){
			if( result.getText().length() == 1 && "0".equals(result.getText())){
				result.setText("5");
			}else {
				result.setText( result.getText()+"5");
			}
		}else if( v.equals( b6 )){
			if( result.getText().length() == 1 && "0".equals(result.getText())){
				result.setText("6");
			}else {
				result.setText( result.getText()+"6");
			}
		}else if( v.equals( b7 )){
			if( result.getText().length() == 1 && "0".equals(result.getText())){
				result.setText("7");
			}else {
				result.setText( result.getText()+"7");
			}
		}else if( v.equals( b8 )){
			if( result.getText().length() == 1 && "0".equals(result.getText())){
				result.setText("8");
			}else {
				result.setText( result.getText()+"8");
			}
		}else if( v.equals( b9 )){
			if( result.getText().length() == 1 && "0".equals(result.getText())){
				result.setText("9");
			}else {
				result.setText( result.getText()+"9");
			}
		}else if( v.equals( b_claer )){
			result.setText( "0");
		}else if( v.equals( b_back )){
			if( result.getText().length() != 0 ) {
				result.setText( result.getText().subSequence( 0 , result.getText().length()-1));
			}
		}else if( v.equals( b_devide )){
			result.setText( result.getText()+"/");
		}else if( v.equals( b_plus )){
			result.setText( result.getText()+"+");
		}else if( v.equals( b_minus )){
			result.setText( result.getText()+"-");
		}else if( v.equals( b_multi )){
			result.setText( result.getText()+"X");
		}else if( v.equals( b_equal )){
			result.setText( calc() );
		}
	}
	private String calc() {
		// 다음시간에 계속
		return "계산";
	}
}





ShinExample_04.zip

계산부분은 수정을 좀 해야하네요

Posted by App.SHIN
:

BLOG main image
by App.SHIN

공지사항

카테고리

분류 전체보기 (27)
안드로이드 (12)
추천앱 (0)
맛집 (0)
영화 (0)
핫이슈 (2)
서버 (2)
mac os 적응기 (8)
java (1)
mysql (1)
tomcat (1)

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

달력

«   2025/04   »
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
Total :
Today : Yesterday :