Android實現橫屏切換科學計算器
本文實例為大傢分享瞭Android實現橫屏切換科學計算器的具體代碼,供大傢參考,具體內容如下
簡單計算器設計,實現以下功能:
1、豎屏時能實現基本的加減乘除運算、回退和清空輸入。
2、橫屏時變為科學計算器,實現函數計算、進制換算等功能。輸入計算公式,按等號鍵輸出計算結果。
3、公式輸入和結果顯示區支持長按彈出復制、粘貼功能。
4、使用計算器過程中應不彈出軟鍵盤。
5、可以通過進度條實時調整計算結果保留的小數點後位數,或者通過音量鍵完成同樣的效果。
6、實現附加功能:三角函數、階乘、XY、八進制轉換、十六進制轉換、√(Y&X)及括號,如sin(90)。
豎屏簡單計算器
豎屏界面設計xml代碼:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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:background="@color/white" tools:context=".MainActivity"> <LinearLayout android:id="@+id/layout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <EditText android:id="@+id/textView" android:layout_width="match_parent" android:height="5dp" android:gravity="center|end" android:textColor="@color/black" android:textSize="50sp" android:text="" android:enabled="true" android:textCursorDrawable="@null" android:background="@null" android:inputType="none" android:textIsSelectable="true" android:layout_height="5dp" /> <SeekBar android:id="@+id/seekBar" style="@style/Widget.AppCompat.SeekBar.Discrete" android:layout_width="match_parent" android:layout_height="6dp" android:layout_marginBottom="5dp" android:progressDrawable="@drawable/bar" android:min="1" android:max="10"/> <androidx.gridlayout.widget.GridLayout android:layout_width="match_parent" android:layout_height="match_parent" app:useDefaultMargins="false" app:columnCount="4" app:rowCount="5"> <Button android:id="@+id/button5" android:background="@drawable/func_btn_style" android:textSize="24sp" android:textColor="#0000ff" android:text="C" /> <Button android:id="@+id/button6" android:background="@drawable/func_btn_style" android:textSize="24sp" android:textColor="#0000ff" android:text="÷" /> <Button android:id="@+id/button7" android:background="@drawable/func_btn_style" android:textSize="24sp" android:textColor="#0000ff" android:text="×" /> <Button android:id="@+id/button8" android:background="@drawable/func_btn_style" android:textSize="24sp" android:textColor="#0000ff" android:text="◁" /> <Button android:id="@+id/button9" android:background="@drawable/buttonstyle" android:textSize="24sp" android:textColor="@color/black" android:text="1" /> <Button android:id="@+id/button10" android:background="@drawable/buttonstyle" android:textSize="24sp" android:textColor="@color/black" android:text="2" /> <Button android:id="@+id/button11" android:background="@drawable/buttonstyle" android:textSize="24sp" android:textColor="@color/black" android:text="3" /> <Button android:id="@+id/button12" android:background="@drawable/func_btn_style" android:textSize="24sp" android:textColor="#0000ff" android:text="-" /> <Button android:id="@+id/button13" android:background="@drawable/buttonstyle" android:textSize="24sp" android:textColor="@color/black" android:text="4" /> <Button android:id="@+id/button14" android:background="@drawable/buttonstyle" android:textSize="24sp" android:textColor="@color/black" android:text="5" /> <Button android:id="@+id/button15" android:background="@drawable/buttonstyle" android:textSize="24sp" android:textColor="@color/black" android:text="6" /> <Button android:id="@+id/button16" android:background="@drawable/func_btn_style" android:textSize="24sp" android:textColor="#0000ff" android:text="+" /> <Button android:id="@+id/button17" android:background="@drawable/buttonstyle" android:textSize="24sp" android:textColor="@color/black" android:text="7" /> <Button android:id="@+id/button18" android:background="@drawable/buttonstyle" android:textSize="24sp" android:textColor="@color/black" android:text="8" /> <Button android:id="@+id/button19" android:background="@drawable/buttonstyle" android:textSize="24sp" android:textColor="@color/black" android:text="9" /> <Button android:id="@+id/button20" android:background="@drawable/equals_button_style" android:textSize="24sp" android:textColor="@color/white" app:layout_rowSpan="2" android:text="=" /> <Button android:id="@+id/button21" android:background="@drawable/buttonstyle" android:textSize="24sp" android:textColor="@color/black" android:text="%" /> <Button android:id="@+id/button22" android:background="@drawable/buttonstyle" android:textSize="24sp" android:textColor="@color/black" android:text="0" /> <Button android:id="@+id/button23" android:background="@drawable/buttonstyle" android:textSize="24sp" android:textColor="@color/black" android:text="." /> </androidx.gridlayout.widget.GridLayout> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>
豎屏效果圖:(調節進度條或通過音量鍵可以調節小數點位數唷!)
橫屏xml代碼:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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:background="@color/white" tools:context=".MainActivity"> <!-- 結果顯示框 --> <LinearLayout android:id="@+id/layout2" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <EditText android:id="@+id/input" android:layout_width="match_parent" android:layout_height="75dp" android:cursorVisible="false" android:gravity="right|center_vertical" android:enabled="true" android:textCursorDrawable="@null" android:background="@null" android:inputType="none" android:textSize="30sp" android:textIsSelectable="true"/> <!-- 接下去采TableRow的格式進行佈局設計 --> <androidx.gridlayout.widget.GridLayout android:layout_width="match_parent" android:layout_height="match_parent" app:rowCount="7" app:columnCount="6"> <TextView android:id="@+id/M" android:layout_height="wrap_content" android:gravity="center" android:text=" Mem : " /> <TextView android:id="@+id/mem" android:layout_height="wrap_content" app:layout_columnSpan="5" android:gravity="left" android:text=" 0" /> <SeekBar android:id="@+id/seekBar" style="@style/Widget.AppCompat.SeekBar.Discrete" android:layout_width="match_parent" android:progressDrawable="@drawable/bar" android:layout_marginBottom="5dp" android:layout_height="6dp" app:layout_columnSpan="6" android:min="1" android:max="10"/> <TextView android:id="@+id/_drg" android:layout_height="wrap_content" android:textSize="18sp" android:gravity="center" android:background="@drawable/func_btn_style" android:text="DEG" /> <Button android:id="@+id/drg" android:layout_height="wrap_content" android:background="@drawable/func_btn_style" android:textSize="18sp" android:textColor="#888" android:text="DRG" /> <Button android:id="@+id/mc" android:layout_height="wrap_content" app:layout_columnSpan="2" android:background="@drawable/func_btn_style" android:textColor="#888" android:textSize="18sp" android:text="MC" /> <Button android:id="@+id/c" android:layout_height="wrap_content" app:layout_columnSpan="2" android:background="@drawable/func_btn_style" android:textColor="#00b5e2" android:textSize="18sp" android:text="C" /> <Button android:id="@+id/sin" android:layout_height="wrap_content" android:text="sin" android:background="@drawable/func_btn_style" android:textSize="18sp" android:textColor="#888" android:textAllCaps="false"/> <Button android:id="@+id/cos" android:layout_height="wrap_content" android:textAllCaps="false" android:background="@drawable/func_btn_style" android:textSize="18sp" android:textColor="#888" android:text="cos" /> <Button android:id="@+id/tan" android:layout_height="wrap_content" android:textAllCaps="false" android:textSize="18sp" android:textColor="#888" android:background="@drawable/func_btn_style" android:text="tan" /> <Button android:id="@+id/factorial" android:layout_height="wrap_content" android:textAllCaps="false" android:textSize="18sp" android:textColor="#888" android:background="@drawable/func_btn_style" android:text="n!" /> <Button android:id="@+id/bksp" android:layout_height="wrap_content" android:layout_weight="1" app:layout_columnSpan="2" android:background="@drawable/func_btn_style" android:textColor="#00b5e2" android:textSize="18sp" android:text="◁" /> <Button android:id="@+id/one" android:layout_height="wrap_content" android:background="@drawable/buttonstyle" android:textSize="18sp" android:text="1" /> <Button android:id="@+id/two" android:layout_height="wrap_content" android:background="@drawable/buttonstyle" android:textSize="18sp" android:text="2" /> <Button android:id="@+id/three" android:layout_height="wrap_content" android:background="@drawable/buttonstyle" android:textSize="18sp" android:text="3" /> <Button android:id="@+id/divide" android:layout_height="wrap_content" android:background="@drawable/func_btn_style" android:textColor="#00b5e2" android:textSize="18sp" android:text="÷" /> <Button android:id="@+id/left" android:layout_height="wrap_content" android:background="@drawable/func_btn_style" android:text="(" android:textColor="#888" android:textSize="18sp"/> <Button android:id="@+id/right" android:layout_height="wrap_content" android:background="@drawable/func_btn_style" android:text=")" android:textColor="#888" android:textSize="18sp"/> <Button android:id="@+id/four" android:layout_height="wrap_content" android:background="@drawable/buttonstyle" android:text="4" android:textSize="18sp"/> <Button android:id="@+id/five" android:layout_height="wrap_content" android:background="@drawable/buttonstyle" android:text="5" android:textSize="18sp"/> <Button android:id="@+id/six" android:layout_height="wrap_content" android:background="@drawable/buttonstyle" android:text="6" android:textSize="18sp"/> <Button android:id="@+id/mul" android:layout_height="wrap_content" android:background="@drawable/func_btn_style" android:textColor="#00b5e2" android:text="×" android:textSize="18sp"/> <Button android:id="@+id/sqrt" android:layout_height="wrap_content" android:background="@drawable/func_btn_style" android:text="√" android:textColor="#888" android:textSize="18sp"/> <Button android:id="@+id/square" android:layout_height="wrap_content" android:background="@drawable/func_btn_style" android:text="^" android:textColor="#888" android:textSize="18sp"/> <Button android:id="@+id/seven" android:layout_height="wrap_content" android:background="@drawable/buttonstyle" android:text="7" android:textSize="18sp"/> <Button android:id="@+id/eight" android:layout_height="wrap_content" android:background="@drawable/buttonstyle" android:text="8" android:textSize="18sp"/> <Button android:id="@+id/nine" android:layout_height="wrap_content" android:background="@drawable/buttonstyle" android:text="9" android:textSize="18sp"/> <Button android:id="@+id/sub" android:layout_height="wrap_content" android:background="@drawable/func_btn_style" android:textColor="#00b5e2" android:text="-" android:textSize="18sp"/> <Button android:id="@+id/log" android:layout_height="wrap_content" android:textAllCaps="false" android:background="@drawable/func_btn_style" android:text="log" android:textColor="#888" android:textSize="18sp"/> <Button android:id="@+id/ln" android:layout_height="wrap_content" android:textAllCaps="false" android:background="@drawable/func_btn_style" android:text="ln" android:textColor="#888" android:textSize="18sp"/> <Button android:id="@+id/dot" android:layout_height="wrap_content" android:background="@drawable/buttonstyle" android:text="." android:textSize="18sp"/> <Button android:id="@+id/zero" android:layout_height="wrap_content" android:background="@drawable/buttonstyle" android:text="0" android:textSize="18sp"/> <LinearLayout android:id="@+id/linear" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <Button android:id="@+id/bd" android:layout_height="match_parent" android:background="@drawable/buttonstyle" android:text="D" android:textSize="18sp" android:layout_weight="1" android:layout_width="match_parent" /> <Button android:id="@+id/db" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/buttonstyle" android:textSize="18sp" android:layout_weight="1" android:text="B" /> </LinearLayout> <Button android:id="@+id/add" android:layout_height="wrap_content" android:background="@drawable/func_btn_style" android:textColor="#00b5e2" android:text="+" android:textSize="18sp"/> <Button android:id="@+id/equal" android:layout_height="wrap_content" android:background="@drawable/equals_button_style" android:textColor="#ffffff" app:layout_columnSpan="2" android:text="=" android:textSize="18sp"/> <TextView android:id="@+id/T" android:layout_height="wrap_content" android:text="提示 : " app:layout_columnSpan="6"/> <TextView android:id="@+id/tip" android:layout_height="wrap_content" android:text="歡迎使用!" app:layout_columnSpan="6"/> </androidx.gridlayout.widget.GridLayout> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>
橫屏效果圖:
Java代碼如下:
package com.zjw; import android.app.Activity; import android.content.ClipboardManager; import android.content.res.Configuration; import android.graphics.Point; import android.os.Bundle; import android.text.Editable; import android.text.method.KeyListener; import android.util.Log; import android.view.Display; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import java.math.BigDecimal; import java.util.StringTokenizer; public class MainActivity extends Activity { /** * 定義變量 */ //舍入精度 public static final int[] DEF_DIV_SCALE = {17}; //初始化顯示數據 private final String[] init =new String[1]; //顯示框 private EditText input;// 用於顯示輸出結果 //劃動條 private SeekBar seekBar; //普通控件及變量 private Button[] btn = new Button[10];// 0~9十個數字 private TextView mem, _drg, tip; private Button div, mul, sub, add, equal, sin, cos, tan, log, ln, sqrt, square, factorial, bksp, left, right, dot, bd, db, drg, mc, c; public String str_old; public String str_new; public boolean vbegin = true;// 控制輸入,true為重新輸入,false為接著輸入 public boolean drg_flag = true;// true為角度,false為弧度 public double pi = 4 * Math.atan(1);// π值 public boolean tip_lock = true;// true為正確,可以繼續輸入,false錯誤,輸入鎖定 public boolean equals_flag = true;// 是否在按下=之後輸入,true為之前,false為之後 //定義ContextMenu中每個菜單選項的Id final int Menu_1 = Menu.FIRST; final int Menu_2 = Menu.FIRST + 1; private ClipboardManager mClipboard = null; public boolean onCreateOptionsMenu(Menu menu) { //導入菜單佈局 getMenuInflater().inflate(R.menu.main, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { //創建菜單項的點擊事件 switch (item.getItemId()) { case R.id.menu_setting: Toast.makeText(this, "點擊瞭設置", Toast.LENGTH_SHORT).show(); break; case R.id.menu_out: // Toast.makeText(this, "點擊瞭退出", Toast.LENGTH_SHORT).show(); android.os.Process.killProcess(android.os.Process.myPid());//獲取PID System.exit(0); break; default: break; } return super.onOptionsItemSelected(item); } /** *onCreate */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //切換佈局後調用,初始化顯示 if(savedInstanceState!=null){ init[0] = savedInstanceState.getString("exp"); equals_flag = false; } //屏幕方向監聽 int orientation = getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_LANDSCAPE) { // 橫屏內容 setContentView(R.layout.activity_main2); InitWigdet(); AllWigdetListener(); } else if (orientation == Configuration.ORIENTATION_PORTRAIT) { // 豎屏內容 setContentView(R.layout.activity_main); input = (EditText)findViewById(R.id.textView); input.setText(init[0]); seekBar = (SeekBar) findViewById(R.id.seekBar); seekBar.setProgress(DEF_DIV_SCALE[0]); seekBar.setOnSeekBarChangeListener(onSeekBarChangeListener); Display defaultDisplay = getWindowManager().getDefaultDisplay(); Point point = new Point(); defaultDisplay.getSize(point); Integer x = point.x; Integer y = point.y; input.setKeyListener(new KeyListener() { @Override public int getInputType() { return 0; } @Override public boolean onKeyDown(View view, Editable editable, int i, KeyEvent keyEvent) { return false; } @Override public boolean onKeyUp(View view, Editable editable, int i, KeyEvent keyEvent) { return false; } @Override public boolean onKeyOther(View view, Editable editable, KeyEvent keyEvent) { return false; } @Override public void clearMetaKeyState(View view, Editable editable, int i) { } }); View.OnClickListener onClearListener = new View.OnClickListener() { @Override public void onClick(View view) { input.setText(""); } }; View.OnClickListener onClearLastListener = new View.OnClickListener() { @Override public void onClick(View view) { String s = input.getText().toString(); int len = s.length(); if(len>0) { s = s.substring(0, len - 1); input.setText(s); } } }; View.OnClickListener onEXPListener = new View.OnClickListener() { @Override public void onClick(View view) { Button temp = (Button)view; String s = temp.getText().toString(); String show = input.getText().toString(); int len = show.length(); if(show.length()==0){ if(s.equals("+")||s.equals("×")||s.equals("÷")) return; } if((show.endsWith("+"))||(show.endsWith("-"))||(show.endsWith("×"))||(show.endsWith("÷"))||(show.endsWith("."))){ if(s.equals("+")||s.equals("×")||s.equals("÷")||s.equals("-")||(s.equals("."))){ show = show.substring(0,len-1) + s; input.setText(show); }else{ input.append(s); } }else{ input.append(s); } } }; View.OnClickListener onEXECListener = new View.OnClickListener() { @Override public void onClick(View view) { String s = input.getText().toString(); if(s.length()==0) return; s = s.replace("×","*"); s = s.replace("÷","/"); s = s.replace("%",""); if((s.endsWith("+"))||(s.endsWith("-"))||(s.endsWith("*"))||(s.endsWith("/"))||(s.endsWith(".")))return; try{ String re = Calculator.conversion(s); re = round(re,DEF_DIV_SCALE[0]); if(re.indexOf(".") > 0){ re = re.replaceAll("0+?$", "");//去掉多餘的0 re = re.replaceAll("[.]$", "");//如最後一位是.則去掉 } input.setText(re); }catch (Exception e){ Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show(); input.setText(""); } } }; View.OnClickListener onPERCENTCListener = new View.OnClickListener() { @Override public void onClick(View view) { String s = input.getText().toString(); if(s.length()==0) return; s = s.replace("×","*"); s = s.replace("÷","/"); s = s.replace("%",""); if((s.endsWith("+"))||(s.endsWith("-"))||(s.endsWith("*"))||(s.endsWith("/"))||(s.endsWith("."))) return; s = s+"/100"; try{ String re = Calculator.conversion(s); re = round(re,DEF_DIV_SCALE[0]); if(re.indexOf(".") > 0){ re = re.replaceAll("0+?$", "");//去掉多餘的0 re = re.replaceAll("[.]$", "");//如最後一位是.則去掉 } input.setText(re+"%"); }catch (Exception e){ Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show(); input.setText(""); } } }; input.getLayoutParams().height = 2*y/7; Button button5 = (Button)findViewById(R.id.button5); button5.getLayoutParams().width = x/4 ;button5.getLayoutParams().height = y/8; Button button6 = (Button)findViewById(R.id.button6); button6.getLayoutParams().width = x/4 ;button6.getLayoutParams().height = y/8; Button button7 = (Button)findViewById(R.id.button7); button7.getLayoutParams().width = x/4 ;button7.getLayoutParams().height = y/8; Button button8 = (Button)findViewById(R.id.button8); button8.getLayoutParams().width = x/4 ;button8.getLayoutParams().height = y/8; Button button9 = (Button)findViewById(R.id.button9); button9.getLayoutParams().width = x/4 ;button9.getLayoutParams().height = y/8; Button button10 = (Button)findViewById(R.id.button10); button10.getLayoutParams().width = x/4 ;button10.getLayoutParams().height = y/8; Button button11 = (Button)findViewById(R.id.button11); button11.getLayoutParams().width = x/4 ;button11.getLayoutParams().height = y/8; Button button12 = (Button)findViewById(R.id.button12); button12.getLayoutParams().width = x/4 ;button12.getLayoutParams().height = y/8; Button button13 = (Button)findViewById(R.id.button13); button13.getLayoutParams().width = x/4 ;button13.getLayoutParams().height = y/8; Button button14 = (Button)findViewById(R.id.button14); button14.getLayoutParams().width = x/4 ;button14.getLayoutParams().height = y/8; Button button15 = (Button)findViewById(R.id.button15); button15.getLayoutParams().width = x/4 ;button15.getLayoutParams().height = y/8; Button button16 = (Button)findViewById(R.id.button16); button16.getLayoutParams().width = x/4 ;button16.getLayoutParams().height = y/8; Button button17 = (Button)findViewById(R.id.button17); button17.getLayoutParams().width = x/4 ;button17.getLayoutParams().height = y/8; Button button18 = (Button)findViewById(R.id.button18); button18.getLayoutParams().width = x/4 ;button18.getLayoutParams().height = y/8; Button button19 = (Button)findViewById(R.id.button19); button19.getLayoutParams().width = x/4 ;button19.getLayoutParams().height = y/8; Button button20 = (Button)findViewById(R.id.button20); button20.getLayoutParams().width = x/4 ;button20.getLayoutParams().height = 2*(y/8); Button button21 = (Button)findViewById(R.id.button21); button21.getLayoutParams().width = x/4 ;button21.getLayoutParams().height = y/8; Button button22 = (Button)findViewById(R.id.button22); button22.getLayoutParams().width = x/4 ;button22.getLayoutParams().height = y/8; Button button23 = (Button)findViewById(R.id.button23); button23.getLayoutParams().width = x/4 ;button23.getLayoutParams().height = y/8; button6.setOnClickListener(onEXPListener);button7.setOnClickListener(onEXPListener); button9.setOnClickListener(onEXPListener);button10.setOnClickListener(onEXPListener); button11.setOnClickListener(onEXPListener);button12.setOnClickListener(onEXPListener); button13.setOnClickListener(onEXPListener);button14.setOnClickListener(onEXPListener); button15.setOnClickListener(onEXPListener);button16.setOnClickListener(onEXPListener); button17.setOnClickListener(onEXPListener);button18.setOnClickListener(onEXPListener); button19.setOnClickListener(onEXPListener);button21.setOnClickListener(onEXPListener); button22.setOnClickListener(onEXPListener);button23.setOnClickListener(onEXPListener); button5.setOnClickListener(onClearListener); button8.setOnClickListener(onClearLastListener); button20.setOnClickListener(onEXECListener); button21.setOnClickListener(onPERCENTCListener); } } /** * 初始化所有的組件 */ private void InitWigdet() { //獲取屏幕參數 Display defaultDisplay = getWindowManager().getDefaultDisplay(); Point point = new Point(); defaultDisplay.getSize(point); Integer x = point.x; Integer y = point.y - 60; // 獲取界面元素 input = (EditText) findViewById(R.id.input); input.setKeyListener(new KeyListener() { @Override public int getInputType() { return 0; } @Override public boolean onKeyDown(View view, Editable editable, int i, KeyEvent keyEvent) { return false; } @Override public boolean onKeyUp(View view, Editable editable, int i, KeyEvent keyEvent) { return false; } @Override public boolean onKeyOther(View view, Editable editable, KeyEvent keyEvent) { return false; } @Override public void clearMetaKeyState(View view, Editable editable, int i) { } }); input.setText(init[0]); seekBar = (SeekBar) findViewById(R.id.seekBar); //seekBar.getLayoutParams().height = y/7/3; seekBar.setProgress(DEF_DIV_SCALE[0]); seekBar.setOnSeekBarChangeListener(onSeekBarChangeListener); input.getLayoutParams().height = y/9; mem = (TextView) findViewById(R.id.mem); tip = (TextView) findViewById(R.id.tip); _drg = (TextView) findViewById(R.id._drg); _drg.getLayoutParams().width = x/6 ;_drg.getLayoutParams().height = y/10-8; btn[0] = (Button) findViewById(R.id.zero); btn[0].getLayoutParams().width = x/6 ;btn[0].getLayoutParams().height = y/10; btn[1] = (Button) findViewById(R.id.one); btn[1].getLayoutParams().width = x/6 ;btn[1].getLayoutParams().height = y/10; btn[2] = (Button) findViewById(R.id.two); btn[2].getLayoutParams().width = x/6 ;btn[2].getLayoutParams().height = y/10; btn[3] = (Button) findViewById(R.id.three); btn[3].getLayoutParams().width = x/6 ;btn[3].getLayoutParams().height = y/10; btn[4] = (Button) findViewById(R.id.four); btn[4].getLayoutParams().width = x/6 ;btn[4].getLayoutParams().height = y/10; btn[5] = (Button) findViewById(R.id.five); btn[5].getLayoutParams().width = x/6 ;btn[5].getLayoutParams().height = y/10; btn[6] = (Button) findViewById(R.id.six); btn[6].getLayoutParams().width = x/6 ;btn[6].getLayoutParams().height = y/10; btn[7] = (Button) findViewById(R.id.seven); btn[7].getLayoutParams().width = x/6 ;btn[7].getLayoutParams().height = y/10; btn[8] = (Button) findViewById(R.id.eight); btn[8].getLayoutParams().width = x/6 ;btn[8].getLayoutParams().height = y/10; btn[9] = (Button) findViewById(R.id.nine); btn[9].getLayoutParams().width = x/6 ;btn[9].getLayoutParams().height = y/10; div = (Button) findViewById(R.id.divide); div.getLayoutParams().width = x/6 ;div.getLayoutParams().height = y/10; mul = (Button) findViewById(R.id.mul);mul.getLayoutParams().width = x/6 ;mul.getLayoutParams().height = y/10; sub = (Button) findViewById(R.id.sub); sub.getLayoutParams().width = x/6 ;sub.getLayoutParams().height = y/10; add = (Button) findViewById(R.id.add); add.getLayoutParams().width = x/6 ;add.getLayoutParams().height = y/10; equal = (Button) findViewById(R.id.equal); equal.getLayoutParams().width = 2*x/6 ;equal.getLayoutParams().height = y/10; sin = (Button) findViewById(R.id.sin); sin.getLayoutParams().width = x/6 ;sin.getLayoutParams().height = y/10-8; cos = (Button) findViewById(R.id.cos); cos.getLayoutParams().width = x/6 ;cos.getLayoutParams().height = y/10-8; tan = (Button) findViewById(R.id.tan); tan.getLayoutParams().width = x/6 ;tan.getLayoutParams().height = y/10-8; log = (Button) findViewById(R.id.log); log.getLayoutParams().width = x/6 ;log.getLayoutParams().height = y/10; ln = (Button) findViewById(R.id.ln); ln.getLayoutParams().width = x/6 ;ln.getLayoutParams().height = y/10; sqrt = (Button) findViewById(R.id.sqrt); sqrt.getLayoutParams().width = x/6 ;sqrt.getLayoutParams().height = y/10; square = (Button) findViewById(R.id.square); square.getLayoutParams().width = x/6 ;square.getLayoutParams().height = y/10; factorial = (Button) findViewById(R.id.factorial);factorial.getLayoutParams().width = x/6 ;factorial.getLayoutParams().height = y/10-8; bksp = (Button) findViewById(R.id.bksp);bksp.getLayoutParams().width = 2*x/6 ;bksp.getLayoutParams().height = y/10-8; left = (Button) findViewById(R.id.left); left.getLayoutParams().width = x/6 ;left.getLayoutParams().height = y/10; right = (Button) findViewById(R.id.right); right.getLayoutParams().width = x/6 ;right.getLayoutParams().height = y/10; dot = (Button) findViewById(R.id.dot);dot.getLayoutParams().width = x/6 ;dot.getLayoutParams().height = y/10; bd = (Button) findViewById(R.id.bd); LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear);linearLayout.getLayoutParams().width = x/6 ;linearLayout.getLayoutParams().height = y/10; db = (Button) findViewById(R.id.db); drg = (Button) findViewById(R.id.drg);drg.getLayoutParams().width = x/6 ;drg.getLayoutParams().height = y/10-8; mc = (Button) findViewById(R.id.mc); mc.getLayoutParams().width = 2*x/6 ;mc.getLayoutParams().height = y/10-8; c = (Button) findViewById(R.id.c); c.getLayoutParams().width = 2*x/6 ;c.getLayoutParams().height = y/10-8; } /** * 為所有按鍵綁定監聽器 */ private void AllWigdetListener() { // 數字鍵 for (int i = 0; i < 10; i++) { btn[i].setOnClickListener(actionPerformed); } // 為+-x÷等按鍵綁定監聽器 div.setOnClickListener(actionPerformed); mul.setOnClickListener(actionPerformed); sub.setOnClickListener(actionPerformed); add.setOnClickListener(actionPerformed); equal.setOnClickListener(actionPerformed); sin.setOnClickListener(actionPerformed); cos.setOnClickListener(actionPerformed); tan.setOnClickListener(actionPerformed); log.setOnClickListener(actionPerformed); ln.setOnClickListener(actionPerformed); sqrt.setOnClickListener(actionPerformed); square.setOnClickListener(actionPerformed); factorial.setOnClickListener(actionPerformed); bksp.setOnClickListener(actionPerformed); left.setOnClickListener(actionPerformed); right.setOnClickListener(actionPerformed); dot.setOnClickListener(actionPerformed); bd.setOnClickListener(actionPerformed); db.setOnClickListener(actionPerformed); drg.setOnClickListener(actionPerformed); mc.setOnClickListener(actionPerformed); c.setOnClickListener(actionPerformed); } /** * 鍵盤命令捕捉 */ String[] TipCommand = new String[500]; int tip_i = 0;// TipCommand的指針 private View.OnClickListener actionPerformed = new View.OnClickListener() { public void onClick(View v) { // 按鍵上的命令獲取 String command = ((Button) v).getText().toString(); // 顯示器上的字符串 String str = input.getText().toString(); // 檢測輸入是否合法 if (equals_flag == false && "0123456789.()sincostanlnlogn!+-×÷√^".indexOf(command) != -1) { // 檢測顯示器上的字符串是否合法 if (right(str)) { if ("+-×÷√^)".indexOf(command) != -1) { for (int i = 0; i < str.length(); i++) { TipCommand[tip_i] = String.valueOf(str.charAt(i)); tip_i++; } vbegin = false; } } else { input.setText("0"); vbegin = true; tip_i = 0; tip_lock = true; tip.setText("welcome use the APP!"); } equals_flag = true; } if (tip_i > 0) TipChecker(TipCommand[tip_i - 1], command); else if (tip_i == 0) { TipChecker("#", command); } if ("0123456789.()sincostanlnlogn!+-×÷√^".indexOf(command) != -1 && tip_lock) { TipCommand[tip_i] = command; tip_i++; } // 若輸入正確,則將輸入信息顯示到顯示器上 if ("0123456789.()sincostanlnlogn!+-×÷√^".indexOf(command) != -1 && tip_lock) { // 共25個按鍵 print(command); // 若果點擊瞭“DRG”,則切換當前弧度角度制,並將切換後的結果顯示到按鍵上方。 } else if (command.compareTo("DRG") == 0 && tip_lock) { if (drg_flag == true) { drg_flag = false; _drg.setText("RAD"); } else { drg_flag = true; _drg.setText("DEG"); } // 如果輸入時退格鍵,並且是在按=之前 } else if (command.compareTo("◁") == 0 && equals_flag) { // 一次刪除3個字符 if (TTO(str) == 3) { if (str.length() > 3) input.setText(str.substring(0, str.length() - 3)); else if (str.length() == 3) { input.setText("0"); vbegin = true; tip_i = 0; tip.setText("welcome use the APP!"); } // 依次刪除2個字符 } else if (TTO(str) == 2) { if (str.length() > 2) input.setText(str.substring(0, str.length() - 2)); else if (str.length() == 2) { input.setText("0"); vbegin = true; tip_i = 0; tip.setText("welcome use the APP!"); } // 依次刪除一個字符 } else if (TTO(str) == 1) { // 若之前輸入的字符串合法則刪除一個字符 if (right(str)) { if (str.length() > 1) input.setText(str.substring(0, str.length() - 1)); else if (str.length() == 1) { input.setText("0"); vbegin = true; tip_i = 0; tip.setText("welcome use the APP!"); } // 若之前輸入的字符串不合法則刪除全部字符 } else { input.setText("0"); vbegin = true; tip_i = 0; tip.setText("welcome use the APP!"); } } if (input.getText().toString().compareTo("-") == 0 || equals_flag == false) { input.setText("0"); vbegin = true; tip_i = 0; tip.setText("welcome use the APP!"); } tip_lock = true; if (tip_i > 0) tip_i--; // 如果是在按=之後輸入退格鍵 } else if (command.compareTo("Bksp") == 0 && equals_flag == false) { // 將顯示器內容設置為0 input.setText("0"); vbegin = true; tip_i = 0; tip_lock = true; tip.setText("welcome use the APP!"); // 如果輸入的是清除鍵 } else if (command.compareTo("C") == 0) { // 將顯示器內容設置為0 input.setText("0"); // 重新輸入標志置為true vbegin = true; // 緩存命令位數清0 tip_i = 0; // 表明可以繼續輸入 tip_lock = true; // 表明輸入=之前 equals_flag = true; tip.setText("welcome use the APP!"); // 如果輸入的是”MC“,則將存儲器內容清0 } else if (command.compareTo("MC") == 0) { mem.setText("0"); // 如果按”bd“則轉換進制 } else if (command.compareTo("B") == 0) { String s = input.getText().toString(); s = s.replace(".",""); //非法字符清屏 if(".+-x÷√^sincostanloglnn!()".indexOf(s) != -1){ input.setText("0"); }else { try { int a = Integer.valueOf(s); String re = Integer.toBinaryString(a); input.setText(re); }catch (Exception e){ input.setText(""); Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show(); } } // 如果按”db“則轉換進制 }else if(command.compareTo("D") == 0){ String s = input.getText().toString(); s = s.replace(".",""); input.setText("1234567890"); //非法字符清屏 if("23456789+-x÷√^sincostanloglnn!().".indexOf(s) != -1){ input.setText("0"); }else{ try{ Integer re = Integer.parseInt(s,2); input.setText(re.toString()); }catch (Exception e){ input.setText(""); Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show(); } } } else if (command.compareTo("=") == 0 && tip_lock && right(str) && equals_flag) { tip_i = 0; // 表明不可以繼續輸入 tip_lock = false; // 表明輸入=之後 equals_flag = false; // 保存原來算式樣子 str_old = str; // 替換算式中的運算符,便於計算 str = str.replaceAll("sin", "s"); str = str.replaceAll("cos", "c"); str = str.replaceAll("tan", "t"); str = str.replaceAll("log", "g"); str = str.replaceAll("ln", "l"); str = str.replaceAll("n!", "!"); // 重新輸入標志設置true vbegin = true; // 將-1x轉換成- str_new = str.replaceAll("-", "-1×"); // 計算算式結果 new calc().process(str_new); } // 表明可以繼續輸入 tip_lock = true; } }; /* * 檢測函數,對str進行前後語法檢測 為Tip的提示方式提供依據,與TipShow()配合使用 編號 字符 其後可以跟隨的合法字符 1 ( * 數字|(|-|.|函數 2 ) 算符|)|√ ^ 3 . 數字|算符|)|√ ^ 4 數字 .|數字|算符|)|√ ^ 5 算符 * 數字|(|.|函數 6 √ ^ ( |. | 數字 7 函數 數字|(|. * * 小數點前後均可省略,表示0 數字第一位可以為0 */ private void TipChecker(String tipcommand1, String tipcommand2) { // Tipcode1表示錯誤類型,Tipcode2表示名詞解釋類型 int Tipcode1 = 0, Tipcode2 = 0; // 表示命令類型 int tiptype1 = 0, tiptype2 = 0; // 括號數 int bracket = 0; // “+-x÷√^”不能作為第一位 if (tipcommand1.compareTo("#") == 0 && (tipcommand2.compareTo("÷") == 0 || tipcommand2.compareTo("×") == 0 || tipcommand2.compareTo("+") == 0 || tipcommand2.compareTo(")") == 0 || tipcommand2.compareTo("√") == 0 || tipcommand2 .compareTo("^") == 0)) { Tipcode1 = -1; } // 定義存儲字符串中最後一位的類型 else if (tipcommand1.compareTo("#") != 0) { if (tipcommand1.compareTo("(") == 0) { tiptype1 = 1; } else if (tipcommand1.compareTo(")") == 0) { tiptype1 = 2; } else if (tipcommand1.compareTo(".") == 0) { tiptype1 = 3; } else if ("0123456789".indexOf(tipcommand1) != -1) { tiptype1 = 4; } else if ("+-×÷".indexOf(tipcommand1) != -1) { tiptype1 = 5; } else if ("√^".indexOf(tipcommand1) != -1) { tiptype1 = 6; } else if ("sincostanloglnn!".indexOf(tipcommand1) != -1) { tiptype1 = 7; } // 定義欲輸入的按鍵類型 if (tipcommand2.compareTo("(") == 0) { tiptype2 = 1; } else if (tipcommand2.compareTo(")") == 0) { tiptype2 = 2; } else if (tipcommand2.compareTo(".") == 0) { tiptype2 = 3; } else if ("0123456789".indexOf(tipcommand2) != -1) { tiptype2 = 4; } else if ("+-×÷".indexOf(tipcommand2) != -1) { tiptype2 = 5; } else if ("√^".indexOf(tipcommand2) != -1) { tiptype2 = 6; } else if ("sincostanloglnn!".indexOf(tipcommand2) != -1) { tiptype2 = 7; } switch (tiptype1) { case 1: // 左括號後面直接接右括號,“+x÷”(負號“-”不算),或者"√^" if (tiptype2 == 2 || (tiptype2 == 5 && tipcommand2.compareTo("-") != 0) || tiptype2 == 6) Tipcode1 = 1; break; case 2: // 右括號後面接左括號,數字,“+-x÷sin^...” if (tiptype2 == 1 || tiptype2 == 3 || tiptype2 == 4 || tiptype2 == 7) Tipcode1 = 2; break; case 3: // “.”後面接左括號或者“sincos...” if (tiptype2 == 1 || tiptype2 == 7) Tipcode1 = 3; // 連續輸入兩個“.” if (tiptype2 == 3) Tipcode1 = 8; break; case 4: // 數字後面直接接左括號或者“sincos...” if (tiptype2 == 1 || tiptype2 == 7) Tipcode1 = 4; break; case 5: // “+-x÷”後面直接接右括號,“+-x÷√^” if (tiptype2 == 2 || tiptype2 == 5 || tiptype2 == 6) Tipcode1 = 5; break; case 6: // “√^”後面直接接右括號,“+-x÷√^”以及“sincos...” if (tiptype2 == 2 || tiptype2 == 5 || tiptype2 == 6 || tiptype2 == 7) Tipcode1 = 6; break; case 7: // “sincos...”後面直接接右括號“+-x÷√^”以及“sincos...” if (tiptype2 == 2 || tiptype2 == 5 || tiptype2 == 6 || tiptype2 == 7) Tipcode1 = 7; break; } } // 檢測小數點的重復性,Tipconde1=0,表明滿足前面的規則 if (Tipcode1 == 0 && tipcommand2.compareTo(".") == 0) { int tip_point = 0; for (int i = 0; i < tip_i; i++) { // 若之前出現一個小數點點,則小數點計數加1 if (TipCommand[i].compareTo(".") == 0) { tip_point++; } // 若出現以下幾個運算符之一,小數點計數清零 if (TipCommand[i].compareTo("sin") == 0 || TipCommand[i].compareTo("cos") == 0 || TipCommand[i].compareTo("tan") == 0 || TipCommand[i].compareTo("log") == 0 || TipCommand[i].compareTo("ln") == 0 || TipCommand[i].compareTo("n!") == 0 || TipCommand[i].compareTo("√") == 0 || TipCommand[i].compareTo("^") == 0 || TipCommand[i].compareTo("÷") == 0 || TipCommand[i].compareTo("×") == 0 || TipCommand[i].compareTo("-") == 0 || TipCommand[i].compareTo("+") == 0 || TipCommand[i].compareTo("(") == 0 || TipCommand[i].compareTo(")") == 0) { tip_point = 0; } } tip_point++; // 若小數點計數大於1,表明小數點重復瞭 if (tip_point > 1) { Tipcode1 = 8; } } // 檢測右括號是否匹配 if (Tipcode1 == 0 && tipcommand2.compareTo(")") == 0) { int tip_right_bracket = 0; for (int i = 0; i < tip_i; i++) { // 如果出現一個左括號,則計數加1 if (TipCommand[i].compareTo("(") == 0) { tip_right_bracket++; } // 如果出現一個右括號,則計數減1 if (TipCommand[i].compareTo(")") == 0) { tip_right_bracket--; } } // 如果右括號計數=0,表明沒有響應的左括號與當前右括號匹配 if (tip_right_bracket == 0) { Tipcode1 = 10; } } // 檢查輸入=的合法性 if (Tipcode1 == 0 && tipcommand2.compareTo("=") == 0) { // 括號匹配數 int tip_bracket = 0; for (int i = 0; i < tip_i; i++) { if (TipCommand[i].compareTo("(") == 0) { tip_bracket++; } if (TipCommand[i].compareTo(")") == 0) { tip_bracket--; } } // 若大於0,表明左括號還有未匹配的 if (tip_bracket > 0) { Tipcode1 = 9; bracket = tip_bracket; } else if (tip_bracket == 0) { // 若前一個字符是以下之一,表明=號不合法 if ("√^sincostanloglnn!".indexOf(tipcommand1) != -1) { Tipcode1 = 6; } // 若前一個字符是以下之一,表明=號不合法 if ("+-×÷".indexOf(tipcommand1) != -1) { Tipcode1 = 5; } } } // 若命令式以下之一,則顯示相應的幫助信息 if (tipcommand2.compareTo("MC") == 0) Tipcode2 = 1; if (tipcommand2.compareTo("C") == 0) Tipcode2 = 2; if (tipcommand2.compareTo("DRG") == 0) Tipcode2 = 3; if (tipcommand2.compareTo("Bksp") == 0) Tipcode2 = 4; if (tipcommand2.compareTo("sin") == 0) Tipcode2 = 5; if (tipcommand2.compareTo("cos") == 0) Tipcode2 = 6; if (tipcommand2.compareTo("tan") == 0) Tipcode2 = 7; if (tipcommand2.compareTo("log") == 0) Tipcode2 = 8; if (tipcommand2.compareTo("ln") == 0) Tipcode2 = 9; if (tipcommand2.compareTo("n!") == 0) Tipcode2 = 10; if (tipcommand2.compareTo("√") == 0) Tipcode2 = 11; if (tipcommand2.compareTo("^") == 0) Tipcode2 = 12; // 顯示幫助和錯誤信息 TipShow(bracket, Tipcode1, Tipcode2, tipcommand1, tipcommand2); } /* * 反饋Tip信息,加強人機交互,與TipChecker()配合使用 */ private void TipShow(int bracket, int tipcode1, int tipcode2,String tipcommand1, String tipcommand2) { String tipmessage = ""; if (tipcode1 != 0) tip_lock = false;// 表明輸入有誤 switch (tipcode1) { case -1: tipmessage = tipcommand2 + " 不能作為第一個算符\n"; break; case 1: tipmessage = tipcommand1 + " 後應輸入:數字/(/./-/函數 \n"; break; case 2: tipmessage = tipcommand1 + " 後應輸入:)/算符 \n"; break; case 3: tipmessage = tipcommand1 + " 後應輸入:)/數字/算符 \n"; break; case 4: tipmessage = tipcommand1 + " 後應輸入:)/./數字 /算符 \n"; break; case 5: tipmessage = tipcommand1 + " 後應輸入:(/./數字/函數 \n"; break; case 6: tipmessage = tipcommand1 + " 後應輸入:(/./數字 \n"; break; case 7: tipmessage = tipcommand1 + " 後應輸入:(/./數字 \n"; break; case 8: tipmessage = "小數點重復\n"; break; case 9: tipmessage = "不能計算,缺少 " + bracket + " 個 )"; break; case 10: tipmessage = "不需要 )"; break; } switch (tipcode2) { case 1: tipmessage = tipmessage + "[MC 用法: 清除記憶 MEM]"; break; case 2: tipmessage = tipmessage + "[C 用法: 歸零]"; break; case 3: tipmessage = tipmessage + "[DRG 用法: 選擇 DEG 或 RAD]"; break; case 4: tipmessage = tipmessage + "[Bksp 用法: 退格]"; break; case 5: tipmessage = tipmessage + "sin 函數用法示例:\n" + "DEG:sin30 = 0.5 RAD:sin1 = 0.84\n" + "註:與其他函數一起使用時要加括號,如:\n" + "sin(cos45),而不是sincos45"; break; case 6: tipmessage = tipmessage + "cos 函數用法示例:\n" + "DEG:cos60 = 0.5 RAD:cos1 = 0.54\n" + "註:與其他函數一起使用時要加括號,如:\n" + "cos(sin45),而不是cossin45"; break; case 7: tipmessage = tipmessage + "tan 函數用法示例:\n" + "DEG:tan45 = 1 RAD:tan1 = 1.55\n" + "註:與其他函數一起使用時要加括號,如:\n" + "tan(cos45),而不是tancos45"; break; case 8: tipmessage = tipmessage + "log 函數用法示例:\n" + "log10 = log(5+5) = 1\n" + "註:與其他函數一起使用時要加括號,如:\n" + "log(tan45),而不是logtan45"; break; case 9: tipmessage = tipmessage + "ln 函數用法示例:\n" + "ln10 = le(5+5) = 2.3 lne = 1\n" + "註:與其他函數一起使用時要加括號,如:\n" + "ln(tan45),而不是lntan45"; break; case 10: tipmessage = tipmessage + "n! 函數用法示例:\n" + "n!3 = n!(1+2) = 3×2×1 = 6\n" + "註:與其他函數一起使用時要加括號,如:\n" + "n!(log1000),而不是n!log1000"; break; case 11: tipmessage = tipmessage + "√ 用法示例:開任意次根號\n" + "如:27開3次根為 27√3 = 3\n" + "註:與其他函數一起使用時要加括號,如:\n" + "(函數)√(函數) , (n!3)√(log100) = 2.45"; break; case 12: tipmessage = tipmessage + "^ 用法示例:開任意次平方\n" + "如:2的3次方為 2^3 = 8\n" + "註:與其他函數一起使用時要加括號,如:\n" + "(函數)√(函數) , (n!3)^(log100) = 36"; break; } // 將提示信息顯示到tip tip.setText(tipmessage); } /** * 將信息顯示在顯示屏上 */ private void print(String str) { // 清屏後輸出 if (vbegin) { input.setText(str); } else { input.append(str); } vbegin = false; } /* * 檢測函數,返回值為3、2、1 表示應當一次刪除幾個? Three+Two+One = TTO 為Bksp按鈕的刪除方式提供依據 * 返回3,表示str尾部為sin、cos、tan、log中的一個,應當一次刪除3個 返回2,表示str尾部為ln、n!中的一個,應當一次刪除2個 * 返回1,表示為除返回3、2外的所有情況,隻需刪除一個(包含非法字符時要另外考慮:應清屏) */ private int TTO(String str) { if ((str.charAt(str.length() - 1) == 'n' && str.charAt(str.length() - 2) == 'i' && str.charAt(str .length() - 3) == 's') || (str.charAt(str.length() - 1) == 's' && str.charAt(str.length() - 2) == 'o' && str .charAt(str.length() - 3) == 'c') || (str.charAt(str.length() - 1) == 'n' && str.charAt(str.length() - 2) == 'a' && str .charAt(str.length() - 3) == 't') || (str.charAt(str.length() - 1) == 'g' && str.charAt(str.length() - 2) == 'o' && str .charAt(str.length() - 3) == 'l')) { return 3; } else if ((str.charAt(str.length() - 1) == 'n' && str.charAt(str .length() - 2) == 'l') || (str.charAt(str.length() - 1) == '!' && str.charAt(str .length() - 2) == 'n')) { return 2; } else { return 1; } } /* * 判斷一個str是否是合法的,返回值為true、false * 隻包含0123456789.()sincostanlnlogn!+-×÷√^的是合法的str,返回true * 包含瞭除0123456789.()sincostanlnlogn!+-×÷√^以外的字符的str為非法的,返回false */ private boolean right(String str) { int i = 0; for (i = 0; i < str.length(); i++) { if (str.charAt(i) != '0' && str.charAt(i) != '1' && str.charAt(i) != '2' && str.charAt(i) != '3' && str.charAt(i) != '4' && str.charAt(i) != '5' && str.charAt(i) != '6' && str.charAt(i) != '7' && str.charAt(i) != '8' && str.charAt(i) != '9' && str.charAt(i) != '.' && str.charAt(i) != '-' && str.charAt(i) != '+' && str.charAt(i) != '×' && str.charAt(i) != '÷' && str.charAt(i) != '√' && str.charAt(i) != '^' && str.charAt(i) != 's' && str.charAt(i) != 'i' && str.charAt(i) != 'n' && str.charAt(i) != 'c' && str.charAt(i) != 'o' && str.charAt(i) != 't' && str.charAt(i) != 'a' && str.charAt(i) != 'l' && str.charAt(i) != 'g' && str.charAt(i) != '(' && str.charAt(i) != ')' && str.charAt(i) != '!') break; } if (i == str.length()) { return true; } else { return false; } } /* * 整個計算核心, * 隻要將表達式的整個字符串傳入calc().process()就可以實行計算瞭 算法包括以下幾部分: * 1、計算部分 * process(String str) 當然,這是建立在查錯無錯誤的情況下 * 2、數據格式化 FP(double n) 使數據有相當的精確度 * 3、階乘算法 N(double n) 計算n!,將結果返回 * 4、錯誤提示 showError(int code ,String str) * 將錯誤返回 */ public class calc { public calc() { } final int MAXLEN = 500; /* * 計算表達式 從左向右掃描,數字入number棧,運算符入operator棧 * +-基本優先級為1, * ×÷基本優先級為2, * log ln sin cos tan n!基本優先級為3, * √^基本優先級為4 * 括號內層運算符比外層同級運算符優先級高4 * 當前運算符優先級高於棧頂壓棧, * 低於棧頂彈出一個運算符與兩個數進行運算 * 重復直到當前運算符大於棧頂 * 掃描完後對剩下的運算符與數字依次計算 */ public void process(String str) { int weightPlus = 0, topOp = 0, topNum = 0, flag = 1, weightTemp = 0; // weightPlus為同一()下的基本優先級,weightTemp臨時記錄優先級的變化 // topOp為weight[],operator[]的計數器;topNum為number[]的計數器 // flag為正負數的計數器,1為正數,-1為負數 int weight[]; // 保存operator棧中運算符的優先級,以topOp計數 double number[]; // 保存數字,以topNum計數 char ch, ch_gai, operator[];// operator[]保存運算符,以topOp計數 String num;// 記錄數字,str以+-×÷()sctgl!√^分段,+-×÷()sctgl!√^字符之間的字符串即為數字 weight = new int[MAXLEN]; number = new double[MAXLEN]; operator = new char[MAXLEN]; String expression = str; StringTokenizer expToken = new StringTokenizer(expression, "+-×÷()sctgl!√^"); int i = 0; while (i < expression.length()) { ch = expression.charAt(i); // 判斷正負數 if (i == 0) { if (ch == '-') flag = -1; } else if (expression.charAt(i - 1) == '(' && ch == '-') flag = -1; // 取得數字,並將正負符號轉移給數字 if (ch <= '9' && ch >= '0' || ch == '.' || ch == 'E') { num = expToken.nextToken(); ch_gai = ch; Log.e("guojs", ch + "--->" + i); // 取得整個數字 while (i < expression.length() && (ch_gai <= '9' && ch_gai >= '0' || ch_gai == '.' || ch_gai == 'E')) { ch_gai = expression.charAt(i++); Log.e("guojs", "i的值為:" + i); } // 將指針退回之前的位置 if (i >= expression.length()) i -= 1; else { i -= 2; } if (num.compareTo(".") == 0) number[topNum++] = 0; // 將正負符號轉移給數字 else { number[topNum++] = Double.parseDouble(num) * flag; flag = 1; } } // 計算運算符的優先級 if (ch == '(') weightPlus += 4; if (ch == ')') weightPlus -= 4; if (ch == '-' && flag == 1 || ch == '+' || ch == '×' || ch == '÷' || ch == 's' || ch == 'c' || ch == 't' || ch == 'g' || ch == 'l' || ch == '!' || ch == '√' || ch == '^') { switch (ch) { // +-的優先級最低,為1 case '+': case '-': weightTemp = 1 + weightPlus; break; // x÷的優先級稍高,為2 case '×': case '÷': weightTemp = 2 + weightPlus; break; // sincos之類優先級為3 case 's': case 'c': case 't': case 'g': case 'l': case '!': weightTemp = 3 + weightPlus; break; // 其餘優先級為4 // case '^': // case '√': default: weightTemp = 4 + weightPlus; break; } // 如果當前優先級大於堆棧頂部元素,則直接入棧 if (topOp == 0 || weight[topOp - 1] < weightTemp) { weight[topOp] = weightTemp; operator[topOp] = ch; topOp++; // 否則將堆棧中運算符逐個取出,直到當前堆棧頂部運算符的優先級小於當前運算符 } else { while (topOp > 0 && weight[topOp - 1] >= weightTemp) { switch (operator[topOp - 1]) { // 取出數字數組的相應元素進行運算 case '+': number[topNum - 2] += number[topNum - 1]; break; case '-': number[topNum - 2] -= number[topNum - 1]; break; case '×': number[topNum - 2] *= number[topNum - 1]; break; // 判斷除數為0的情況 case '÷': if (number[topNum - 1] == 0) { showError(1, str_old); return; } number[topNum - 2] /= number[topNum - 1]; break; case '√': if (number[topNum - 1] == 0 || (number[topNum - 2] < 0 && number[topNum - 1] % 2 == 0)) { showError(2, str_old); return; } number[topNum - 2] = Math.pow( number[topNum - 2], 1 / number[topNum - 1]); break; case '^': number[topNum - 2] = Math.pow( number[topNum - 2], number[topNum - 1]); break; // 計算時進行角度弧度的判斷及轉換 // sin case 's': if (drg_flag == true) { number[topNum - 1] = Math .sin((number[topNum - 1] / 180) * pi); } else { number[topNum - 1] = Math .sin(number[topNum - 1]); } topNum++; break; // cos case 'c': if (drg_flag == true) { number[topNum - 1] = Math .cos((number[topNum - 1] / 180) * pi); } else { number[topNum - 1] = Math .cos(number[topNum - 1]); } topNum++; break; // tan case 't': if (drg_flag == true) { if ((Math.abs(number[topNum - 1]) / 90) % 2 == 1) { showError(2, str_old); return; } number[topNum - 1] = Math .tan((number[topNum - 1] / 180) * pi); } else { if ((Math.abs(number[topNum - 1]) / (pi / 2)) % 2 == 1) { showError(2, str_old); return; } number[topNum - 1] = Math .tan(number[topNum - 1]); } topNum++; break; // log case 'g': if (number[topNum - 1] <= 0) { showError(2, str_old); return; } number[topNum - 1] = Math .log10(number[topNum - 1]); topNum++; break; // ln case 'l': if (number[topNum - 1] <= 0) { showError(2, str_old); return; } number[topNum - 1] = Math .log(number[topNum - 1]); topNum++; break; // 階乘 case '!': if (number[topNum - 1] > 170) { showError(3, str_old); return; } else if (number[topNum - 1] < 0) { showError(2, str_old); return; } number[topNum - 1] = N(number[topNum - 1]); topNum++; break; } // 繼續取堆棧的下一個元素進行判斷 topNum--; topOp--; } // 將運算符如堆棧 weight[topOp] = weightTemp; operator[topOp] = ch; topOp++; } } i++; } // 依次取出堆棧的運算符進行運算 while (topOp > 0) { // +-x直接將數組的後兩位數取出運算 switch (operator[topOp - 1]) { case '+': number[topNum - 2] += number[topNum - 1]; break; case '-': number[topNum - 2] -= number[topNum - 1]; break; case '×': number[topNum - 2] *= number[topNum - 1]; break; // 涉及到除法時要考慮除數不能為零的情況 case '÷': if (number[topNum - 1] == 0) { showError(1, str_old); return; } number[topNum - 2] /= number[topNum - 1]; break; case '√': if (number[topNum - 1] == 0 || (number[topNum - 2] < 0 && number[topNum - 1] % 2 == 0)) { showError(2, str_old); return; } number[topNum - 2] = Math.pow(number[topNum - 2], 1 / number[topNum - 1]); break; case '^': number[topNum - 2] = Math.pow(number[topNum - 2], number[topNum - 1]); break; // sin case 's': if (drg_flag == true) { number[topNum - 1] = Math .sin((number[topNum - 1] / 180) * pi); } else { number[topNum - 1] = Math.sin(number[topNum - 1]); } topNum++; break; // cos case 'c': if (drg_flag == true) { number[topNum - 1] = Math .cos((number[topNum - 1] / 180) * pi); } else { number[topNum - 1] = Math.cos(number[topNum - 1]); } topNum++; break; // tan case 't': if (drg_flag == true) { if ((Math.abs(number[topNum - 1]) / 90) % 2 == 1) { showError(2, str_old); return; } number[topNum - 1] = Math .tan((number[topNum - 1] / 180) * pi); } else { if ((Math.abs(number[topNum - 1]) / (pi / 2)) % 2 == 1) { showError(2, str_old); return; } number[topNum - 1] = Math.tan(number[topNum - 1]); } topNum++; break; // 對數log case 'g': if (number[topNum - 1] <= 0) { showError(2, str_old); return; } number[topNum - 1] = Math.log10(number[topNum - 1]); topNum++; break; // 自然對數ln case 'l': if (number[topNum - 1] <= 0) { showError(2, str_old); return; } number[topNum - 1] = Math.log(number[topNum - 1]); topNum++; break; // 階乘 case '!': if (number[topNum - 1] > 170) { showError(3, str_old); return; } else if (number[topNum - 1] < 0) { showError(2, str_old); return; } number[topNum - 1] = N(number[topNum - 1]); topNum++; break; } // 取堆棧下一個元素計算 topNum--; topOp--; } // 如果是數字太大,提示錯誤信息 if (number[0] > 7.3E306) { showError(3, str_old); return; } // 輸出最終結果 input.setText(String.valueOf(FP(number[0]))); tip.setText("計算完畢,要繼續請按歸零鍵 C"); mem.setText(str_old + "=" + String.valueOf(FP(number[0]))); } /* * FP = floating point 控制小數位數,達到精度 否則會出現 * 0.6-0.2=0.39999999999999997的情況,用FP即可解決,使得數為0.4 本格式精度為15位 */ public double FP(double n) { // NumberFormat format=NumberFormat.getInstance(); //創建一個格式化類f // format.setMaximumFractionDigits(18); //設置小數位的格式 // DecimalFormat format = new DecimalFormat("0.#############"); Double re = n; String s = round(re.toString(),DEF_DIV_SCALE[0]); return Double.parseDouble(s); } /* * 階乘算法 */ public double N(double n) { int i = 0; double sum = 1; // 依次將小於等於n的值相乘 for (i = 1; i <= n; i++) { sum = sum * i; } return sum; } /* * 錯誤提示,按瞭"="之後,若計算式在process()過程中,出現錯誤,則進行提示 */ public void showError(int code, String str) { String message = ""; switch (code) { case 1: message = "零不能作除數"; break; case 2: message = "函數格式錯誤"; break; case 3: message = "值太大瞭,超出范圍"; } input.setText("\"" + str + "\"" + ": " + message); tip.setText(message + "\n" + "計算完畢,要繼續請按歸零鍵 C"); } } /** *保存切換頁面時EditEext中的值 */ @Override //這種方式保存數據隻是臨時保存,無法永久保存 protected void onSaveInstanceState(@NonNull Bundle outState) { //該函數用於提取出歷史數據,保存到outState中 super.onSaveInstanceState(outState); init[0] = input.getText().toString(); outState.putString("exp",init[0]); } /** *舍入精度 */ public static String round(String v, int scale) { if (scale < 0) { throw new IllegalArgumentException( "The scale must be a positive integer or zero"); } BigDecimal b = new BigDecimal(v); BigDecimal one = new BigDecimal("1"); BigDecimal re = b.divide(one, scale, BigDecimal.ROUND_HALF_UP); return re.toString(); } // @Override // public boolean onCreateOptionsMenu(Menu menu) { // // Inflate the menu; this adds items to the action bar if it is present. // getMenuInflater().inflate(R.menu.main, menu); // return true; // } /** *音量鍵事件 */ @Override public boolean onKeyDown (int keyCode, KeyEvent event) { String s = input.getText().toString(); if(s.length()<1){ }else { switch (keyCode) { // 音量減小 case KeyEvent.KEYCODE_VOLUME_DOWN: if(DEF_DIV_SCALE[0]>1) DEF_DIV_SCALE[0]--; seekBar.setProgress(DEF_DIV_SCALE[0]); Toast.makeText(this.getApplicationContext(), "DOWN " + DEF_DIV_SCALE[0], Toast.LENGTH_SHORT).show(); if(s.contains(".")) input.setText(round(s,DEF_DIV_SCALE[0])); // 音量減小時應該執行的功能代碼 return true; // 音量增大 case KeyEvent.KEYCODE_VOLUME_UP: if(DEF_DIV_SCALE[0]<40) DEF_DIV_SCALE[0]++; seekBar.setProgress(DEF_DIV_SCALE[0]); Toast.makeText(this.getApplicationContext(), "UP " + DEF_DIV_SCALE[0], Toast.LENGTH_SHORT).show(); if(s.contains(".")) input.setText(round(s,DEF_DIV_SCALE[0])); // 音量增大時應該執行的功能代碼 return true; } } return super.onKeyDown (keyCode, event); } /** * 滑動條事件 */ public SeekBar.OnSeekBarChangeListener onSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { //txt_cur.setText("當前進度值:" + progress + " / 100 "); String s = input.getText().toString(); if(s.length()<1){ return; }else{ if(progress>DEF_DIV_SCALE[0]){ DEF_DIV_SCALE[0] = progress; Toast.makeText(getApplicationContext(), "UP " + DEF_DIV_SCALE[0], Toast.LENGTH_SHORT).show(); if(s.contains(".")) input.setText(round(s,DEF_DIV_SCALE[0])); }else if(progress<DEF_DIV_SCALE[0]){ DEF_DIV_SCALE[0] = progress; Toast.makeText(getApplicationContext(), "DOWN " + DEF_DIV_SCALE[0], Toast.LENGTH_SHORT).show(); if(s.contains(".")) input.setText(round(s,DEF_DIV_SCALE[0])); } } } @Override public void onStartTrackingTouch(SeekBar seekBar) { //Toast.makeText(mContext, "觸碰SeekBar", Toast.LENGTH_SHORT).show(); } @Override public void onStopTrackingTouch(SeekBar seekBar) { //Toast.makeText(mContext, "放開SeekBar", Toast.LENGTH_SHORT).show(); } }; /** * 二進制2十進制 */ public int BinaryToDecimal(String s){ int binaryNumber = Integer.valueOf(s); int decimal = 0; int p = 0; while(true){ if(binaryNumber == 0){ break; } else { int temp = binaryNumber%10; decimal += temp*Math.pow(2, p); binaryNumber = binaryNumber/10; p++; } } return decimal; } /** *十進制2二進制 */ }
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。
推薦閱讀:
- Android實現簡單計算器
- Android Studio實現簡易進制轉換計算器
- android studio實現簡單的計算器小功能
- Android以對話框形式制作數字軟鍵盤示例
- Android Studio實現簡易計算器設計