SoFunction
Updated on 2025-03-04

Java implements Android calculator code with parentheses

I won't say much nonsense, everything is in the code, the specific code is as follows:

interface

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff808080"
>
<!-- Results display box -->
<EditText android:
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cursorVisible="false"
android:gravity="right"
android:editable = "false"
android:text="0" />
<!-- NextTableRowFormat for layout design -->
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<!-- Used to display stored results -->
<TextView android:
android:layout_width="53sp"
android:layout_height="wrap_content"
android:text=" MEM :" />
<!-- Display strings by default0 -->
<TextView android:
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="0" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<!-- Shows whether it is currently an angle or a radian,The default is angle -->
<TextView android:
android:layout_width="53sp"
android:layout_height="wrap_content"
android:text=" DEG" />
<!-- Clear storage results -->
<Button android:
android:text="MC"
android:layout_width="106sp"
android:layout_height="wrap_content" />
<!-- Clear all contents of the output window -->
<Button android:
android:text="C"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<!-- Switch between angle and radian -->
<Button android:
android:text="DRG"
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- Sine calculation -->
<Button android:
android:text="sin"
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- Cosine calculation -->
<Button android:
android:text="cos"
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- Tangent calculation -->
<Button android:
android:text="tan"
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- Factorial calculation -->
<Button android:
android:text="n!"
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- Backspace key -->
<Button android:
android:text="Bksp"
android:layout_width="53sp"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<!-- number7 -->
<Button android:
android:text="7"
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- number8 -->
<Button android:
android:text="8"
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- number9 -->
<Button android:
android:text="9"
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- Digit -->
<Button android:
android:text="÷"
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- Left bracket -->
<Button android:
android:text="("
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- Close bracket -->
<Button android:
android:text=")"
android:layout_width="53sp"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<!-- number4 -->
<Button android:
android:text="4"
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- number5 -->
<Button android:
android:text="5"
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- number6 -->
<Button android:
android:text="6"
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- Multiplication sign -->
<Button android:
android:text="×"
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- Prescription -->
<Button android:
android:text="√"
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- power -->
<Button android:
android:text="^"
android:layout_width="53sp"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<!-- number1 -->
<Button android:
android:text="1"
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- number2 -->
<Button android:
android:text="2"
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- number3 -->
<Button android:
android:text="3"
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- minus sign -->
<Button android:
android:text="-"
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- Logarithm -->
<Button android:
android:text="log"
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- 自然Logarithm -->
<Button android:
android:text="ln"
android:layout_width="53sp"
android:layout_height="wrap_content" />
</TableRow>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="57sp"
>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<!-- number0 -->
<Button android:
android:text="0"
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- Decimal point -->
<Button android:
android:text="."
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- equal sign -->
<Button android:
android:text="="
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- Add a sign -->
<Button android:
android:text="+"
android:layout_width="53sp"
android:layout_height="wrap_content" />
<!-- Exit the calculator -->
<Button android:
android:text="exit"
android:layout_width="106sp"
android:layout_height="wrap_content" />
</TableRow>
</TableLayout>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<!-- For prompts,Tell users how to use some functions of the calculator, etc. -->
<TextView android:
android:layout_width="60sp"
android:layout_height="wrap_content"
android:text="reminder:" />
<TextView android:
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Welcome! - Provide source code" />
</TableRow>
</LinearLayout> 

Code

package ;
import ;
import .;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

public class MainActivity extends AppCompatActivity {

// Define variablesprivate Button[] btn = new Button[10];// 0~9 ten numbersprivate EditText input;// Used to display output resultsprivate TextView mem, _drg, tip;
private Button div, mul, sub, add, equal, sin, cos, tan, log, ln, sqrt,
square, factorial, bksp, left, right, dot, exit, drg, mc, c;
public String str_old;
public String str_new;
public boolean vbegin = true;// Control input, true is re-enter, false is subsequent inputpublic boolean drg_flag = true;// true is angle, false is radianpublic double pi = 4 * (1);// π valuepublic boolean tip_lock = true;// true is correct, you can continue to enter, false is wrong, input is lockedpublic boolean equals_flag = true;// Whether to enter after pressing =, true is before, false is after@Override
protected void onCreate(Bundle savedInstanceState) {
(savedInstanceState);
setContentView(.activity_main);
InitWigdet();
AllWigdetListener();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(.menu_main, menu);
return true;
}
/**
 * Initialize all components
 */
private void InitWigdet() {
// Get interface elementsinput = (EditText) findViewById();
mem = (TextView) findViewById();
tip = (TextView) findViewById();
_drg = (TextView) findViewById(._drg);
btn[0] = (Button) findViewById();
btn[1] = (Button) findViewById();
btn[2] = (Button) findViewById();
btn[3] = (Button) findViewById();
btn[4] = (Button) findViewById();
btn[5] = (Button) findViewById();
btn[6] = (Button) findViewById();
btn[7] = (Button) findViewById();
btn[8] = (Button) findViewById();
btn[9] = (Button) findViewById();
div = (Button) findViewById();
mul = (Button) findViewById();
sub = (Button) findViewById();
add = (Button) findViewById();
equal = (Button) findViewById();
sin = (Button) findViewById();
cos = (Button) findViewById();
tan = (Button) findViewById();
log = (Button) findViewById();
ln = (Button) findViewById();
sqrt = (Button) findViewById();
square = (Button) findViewById();
factorial = (Button) findViewById();
bksp = (Button) findViewById();
left = (Button) findViewById();
right = (Button) findViewById();
dot = (Button) findViewById();
exit = (Button) findViewById();
drg = (Button) findViewById();
mc = (Button) findViewById();
c = (Button) findViewById();
}
/**
 * Bind listeners for all keys
 */
private void AllWigdetListener() {
// Number keysfor (int i = 0; i < 10; i++) {
btn[i].setOnClickListener(actionPerformed);
}
// Bind the listener for key presses such as +-x÷(actionPerformed);
(actionPerformed);
(actionPerformed);
(actionPerformed);
(actionPerformed);
(actionPerformed);
(actionPerformed);
(actionPerformed);
(actionPerformed);
(actionPerformed);
(actionPerformed);
(actionPerformed);
(actionPerformed);
(actionPerformed);
(actionPerformed);
(actionPerformed);
(actionPerformed);
(actionPerformed);
(actionPerformed);
(actionPerformed);
(actionPerformed);
}
/**
 * Keyboard command capture
 */
String[] TipCommand = new String[500];
int tip_i = 0;// TipCommand pointerprivate OnClickListener actionPerformed = new OnClickListener() {
public void onClick(View v) {
// Get commands on the keyString command = ((Button) v).getText().toString();
// String on the monitorString str = ().toString();
// Check whether the input is legalif (equals_flag == false
&& "0123456789.()sincostanlnlogn!+-×÷√^".indexOf(command) != -1) {
// Check whether the string on the monitor is legalif (right(str)) {
if ("+-×÷√^)".indexOf(command) != -1) {
for (int i = 0; i < (); i++) {
TipCommand[tip_i] = ((i));
tip_i++;
}
vbegin = false;
}
} else {
("0");
vbegin = true;
tip_i = 0;
tip_lock = true;
("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 the input is correct, display the input information on the monitorif ("0123456789.()sincostanlnlogn!+-×÷√^".indexOf(command) != -1
&& tip_lock) { // Total 25 keysprint(command);
// If “DRG” is clicked, switch the current radian angle system and display the switched results above the button.} else if (("DRG") == 0 && tip_lock) {
if (drg_flag == true) {
drg_flag = false;
_drg.setText(" RAD");
} else {
drg_flag = true;
_drg.setText(" DEG");
}
// If the backspace key is entered and it is before pressing =} else if (("Bksp") == 0 && equals_flag) {
// Delete 3 characters at a timeif (TTO(str) == 3) {
if (() > 3)
((0, () - 3));
else if (() == 3) {
("0");
vbegin = true;
tip_i = 0;
("welcome use the APP!");
}
// Delete 2 characters in turn} else if (TTO(str) == 2) {
if (() > 2)
((0, () - 2));
else if (() == 2) {
("0");
vbegin = true;
tip_i = 0;
("welcome use the APP!");
}
// Delete a character in turn} else if (TTO(str) == 1) {
// If the string entered before is legal, delete a characterif (right(str)) {
if (() > 1)
((0, () - 1));
else if (() == 1) {
("0");
vbegin = true;
tip_i = 0;
("welcome use the APP!");
}
// If the string entered previously is not legal, delete all characters} else {
("0");
vbegin = true;
tip_i = 0;
("welcome use the APP!");
}
}
if (().toString().compareTo("-") == 0
|| equals_flag == false) {
("0");
vbegin = true;
tip_i = 0;
("welcome use the APP!");
}
tip_lock = true;
if (tip_i > 0)
tip_i--;
// If it is after pressing = enter the backspace key} else if (("Bksp") == 0 && equals_flag == false) {
// Set the display content to 0("0");
vbegin = true;
tip_i = 0;
tip_lock = true;
("welcome use the APP!");
// If the input is the clear key} else if (("C") == 0) {
// Set the display content to 0("0");
// Re-enter the flag to truevbegin = true;
// The cache command bits are 0tip_i = 0;
// Indicates that you can continue to entertip_lock = true;
// Indicate input = beforeequals_flag = true;
("welcome use the APP!");
// If the input is "MC", clear the memory contents by 0} else if (("MC") == 0) {
("0");
// If you press "exit" then exit the program} else if (("exit") == 0) {
(0);
// If the input is a = sign, and the input is legal} else if (("=") == 0 && tip_lock && right(str)
&& equals_flag) {
tip_i = 0;
// Indicates that it is not possible to continue typingtip_lock = false;
// Indicate that input = afterequals_flag = false;
// Save the original calculation stylestr_old = str;
// Replace operators in the formula to facilitate calculationstr = ("sin", "s");
str = ("cos", "c");
str = ("tan", "t");
str = ("log", "g");
str = ("ln", "l");
str = ("n!", "!");
// Re-enter the flag to set truevbegin = true;
// Convert -1x to -str_new = ("-", "-1×");
// Calculate the result of the equationnew calc().process(str_new);
}
// Indicates that you can continue to entertip_lock = true;
}
};
/*
 * Detection function, performs pre- and post-synchronization detection of str. Provides a basis for Tip's prompt method, and is used in conjunction with TipShow() Numbered characters The legal character that can be followed by 1 (
 * Number|(|-|.|Function 2) Operator|)|√ ^ 3. Number|Operator|)|√ ^ 4 Number.|Number|Operator|)|√ ^ 5 Operator
 * Number|(|.|Function 6 √^(|.|Number 7 Function Number|(|.
 *
 * Both the decimal point can be omitted, indicating that 0 The first digit can be 0
 */
private void TipChecker(String tipcommand1, String tipcommand2) {
// Tipcode1 represents the error type, Tipcode2 represents the noun explanation typeint Tipcode1 = 0, Tipcode2 = 0;
// Indicates the command typeint tiptype1 = 0, tiptype2 = 0;
// Number of bracketsint bracket = 0;
// "+-x÷√^" cannot be the first placeif (("#") == 0
&& (("÷") == 0
|| ("×") == 0
|| ("+") == 0
|| (")") == 0
|| ("√") == 0 || tipcommand2
.compareTo("^") == 0)) {
Tipcode1 = -1;
}
// Define the type that stores the last bit in the stringelse if (("#") != 0) {
if (("(") == 0) {
tiptype1 = 1;
} else if ((")") == 0) {
tiptype1 = 2;
} else if ((".") == 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;
}
// Define the type of key to enterif (("(") == 0) {
tiptype2 = 1;
} else if ((")") == 0) {
tiptype2 = 2;
} else if ((".") == 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:
// The left bracket is directly followed by the close bracket, "+x÷" (the negative sign "-" does not count), or "√^"if (tiptype2 == 2
|| (tiptype2 == 5 && ("-") != 0)
|| tiptype2 == 6)
Tipcode1 = 1;
break;
case 2:
// The closing bracket is followed by the left bracket, the number, "+-x÷sin^..."if (tiptype2 == 1 || tiptype2 == 3 || tiptype2 == 4
|| tiptype2 == 7)
Tipcode1 = 2;
break;
case 3:
// "." is followed by the left bracket or "sincos..."if (tiptype2 == 1 || tiptype2 == 7)
Tipcode1 = 3;
// Enter two "."if (tiptype2 == 3)
Tipcode1 = 8;
break;
case 4:
// The number is directly followed by the left bracket or "sincos..."if (tiptype2 == 1 || tiptype2 == 7)
Tipcode1 = 4;
break;
case 5:
// "+-x÷" is directly followed by the close bracket, "+-x÷√^"if (tiptype2 == 2 || tiptype2 == 5 || tiptype2 == 6)
Tipcode1 = 5;
break;
case 6:
// "√^" is directly followed by the close bracket, "+-x÷√^" and "sincos..."if (tiptype2 == 2 || tiptype2 == 5 || tiptype2 == 6
|| tiptype2 == 7)
Tipcode1 = 6;
break;
case 7:
// "sincos..." is directly followed by the closing bracket "+-x÷√^" and "sincos..."if (tiptype2 == 2 || tiptype2 == 5 || tiptype2 == 6
|| tiptype2 == 7)
Tipcode1 = 7;
break;
}
}
// Detection of the repetition of the decimal point, Tipconde1=0, indicating that the previous rules are metif (Tipcode1 == 0 && (".") == 0) {
int tip_point = 0;
for (int i = 0; i < tip_i; i++) {
// If a decimal point appears before, the decimal point count will be added by 1if (TipCommand[i].compareTo(".") == 0) {
tip_point++;
}
// If one of the following operators appears, the decimal point count is clearedif (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++;
// If the decimal point count is greater than 1, it means that the decimal point is repeatedif (tip_point > 1) {
Tipcode1 = 8;
}
}
// Check whether the closing bracket matchesif (Tipcode1 == 0 && (")") == 0) {
int tip_right_bracket = 0;
for (int i = 0; i < tip_i; i++) {
// If an open bracket appears, the count is increased by 1if (TipCommand[i].compareTo("(") == 0) {
tip_right_bracket++;
}
// If a close bracket appears, the count is reduced by 1if (TipCommand[i].compareTo(")") == 0) {
tip_right_bracket--;
}
}
// If the closing bracket count = 0, it means that the unresponsive opening bracket matches the current closing bracketif (tip_right_bracket == 0) {
Tipcode1 = 10;
}
}
// Check the legality of input =if (Tipcode1 == 0 && ("=") == 0) {
// Number of brackets matchint 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--;
}
}
// If it is greater than 0, it means that there is still no match for the left bracket.if (tip_bracket > 0) {
Tipcode1 = 9;
bracket = tip_bracket;
} else if (tip_bracket == 0) {
// If the previous character is one of the following, it means that the = number is illegalif ("√^sincostanloglnn!".indexOf(tipcommand1) != -1) {
Tipcode1 = 6;
}
// If the previous character is one of the following, it means that the = number is illegalif ("+-×÷".indexOf(tipcommand1) != -1) {
Tipcode1 = 5;
}
}
}
// If one of the following commands is displayed, the corresponding help information is displayed.if (("MC") == 0)
Tipcode2 = 1;
if (("C") == 0)
Tipcode2 = 2;
if (("DRG") == 0)
Tipcode2 = 3;
if (("Bksp") == 0)
Tipcode2 = 4;
if (("sin") == 0)
Tipcode2 = 5;
if (("cos") == 0)
Tipcode2 = 6;
if (("tan") == 0)
Tipcode2 = 7;
if (("log") == 0)
Tipcode2 = 8;
if (("ln") == 0)
Tipcode2 = 9;
if (("n!") == 0)
Tipcode2 = 10;
if (("√") == 0)
Tipcode2 = 11;
if (("^") == 0)
Tipcode2 = 12;
// Show help and error messagesTipShow(bracket, Tipcode1, Tipcode2, tipcommand1, tipcommand2);
}
/*
 * Feedback Tip information, strengthen human-computer interaction, and use it in conjunction with TipChecker()
 */
private void TipShow(int bracket, int tipcode1, int tipcode2,
String tipcommand1, String tipcommand2) {
String tipmessage = "";
if (tipcode1 != 0)
tip_lock = false;// Indicates that the input is incorrectswitch (tipcode1) {
case -1:
tipmessage = tipcommand2 + "Cannot be the first operator\n";
break;
case 1:
tipmessage = tipcommand1 + " It should be entered later:number/(/./-/function \n";
break;
case 2:
tipmessage = tipcommand1 + "After entering:)/operator \n";
break;
case 3:
tipmessage = tipcommand1 + "After entering:)/number/operator \n";
break;
case 4:
tipmessage = tipcommand1 + "After entering:)/./number/operator \n";
break;
case 5:
tipmessage = tipcommand1 + " It should be entered later:(/./number/function \n";
break;
case 6:
tipmessage = tipcommand1 + " It should be entered later:(/./number \n";
break;
case 7:
tipmessage = tipcommand1 + " It should be entered later:(/./number \n";
break;
case 8:
tipmessage = "Repeat the decimal point\n";
break;
case 9:
tipmessage = "Cannot calculate, missing" + bracket + " indivual )";
break;
case 10:
tipmessage = "unnecessary )";
break;
}
switch (tipcode2) {
case 1:
tipmessage = tipmessage + "[MC Usage: Clear Memory MEM]";
break;
case 2:
tipmessage = tipmessage + "[C Usage: Zero]";
break;
case 3:
tipmessage = tipmessage + "[DRG Usage: Select DEG or RAD]";
break;
case 4:
tipmessage = tipmessage + "[Bksp Usage: Backspace]";
break;
case 5:
tipmessage = tipmessage + "Sin function usage example:\n"
+ "DEG:sin30 = 0.5 RAD:sin1 = 0.84\n"
+ "Note:与其他function一起使用时要加括号,like:\n" + "sin(cos45),Insteadsincos45";
break;
case 6:
tipmessage = tipmessage + "Cos function usage example:\n"
+ "DEG:cos60 = 0.5 RAD:cos1 = 0.54\n"
+ "Note:与其他function一起使用时要加括号,like:\n" + "cos(sin45),Insteadcossin45";
break;
case 7:
tipmessage = tipmessage + "Tan function usage example:\n"
+ "DEG:tan45 = 1 RAD:tan1 = 1.55\n"
+ "Note:与其他function一起使用时要加括号,like:\n" + "tan(cos45),Insteadtancos45";
break;
case 8:
tipmessage = tipmessage + "Example usage of log function:\n"
+ "log10 = log(5+5) = 1\n" + "Note:与其他function一起使用时要加括号,like:\n"
+ "log(tan45),Insteadlogtan45";
break;
case 9:
tipmessage = tipmessage + "ln function usage example:\n"
+ "ln10 = le(5+5) = 2.3 lne = 1\n"
+ "Note:与其他function一起使用时要加括号,like:\n" + "ln(tan45),Insteadlntan45";
break;
case 10:
tipmessage = tipmessage + "n! Function usage example:\n"
+ "n!3 = n!(1+2) = 3×2×1 = 6\n" + "Note:与其他function一起使用时要加括号,like:\n"
+ "n!(log1000),Insteadn!log1000";
break;
case 11:
tipmessage = tipmessage + "√ Usage example: open any root number\n"
+ "like:27open3The second root is 27√3 = 3\n" + "Note:与其他function一起使用时要加括号,like:\n"
+ "(function)√(function) , (n!3)√(log100) = 2.45";
break;
case 12:
tipmessage = tipmessage + "^ Usage example: open any time square\n" + "like:2of3To the power of 2^3 = 8\n"
+ "Note:与其他function一起使用时要加括号,like:\n"
+ "(function)√(function) , (n!3)^(log100) = 36";
break;
}
// Display the prompt message to the tip(tipmessage);
}
/**
 * Display information on the display
 */
private void print(String str) {
// Output after clearing the screenif (vbegin) {
(str);
} else {
(str);
}
vbegin = false;
}
/*
 * The detection function, the return values ​​are 3, 2, and 1, which means how many should be deleted at a time?  Three+Two+One = TTO provides a basis for deleting the Bksp button
 * Return 3, indicating that the str tail is one of sin, cos, tan, and log, and 3 should be deleted at once. Return 2, indicating that the str tail is one of ln and n!, and 2 should be deleted at once.
 * Return 1, which means all cases except 3 and 2, just delete one (if you include illegal characters, you should consider it: the screen should be cleared)
 */
private int TTO(String str) {
if (((() - 1) == 'n'
&& (() - 2) == 'i' && (str
.length() - 3) == 's')
|| ((() - 1) == 's'
&& (() - 2) == 'o' && str
.charAt(() - 3) == 'c')
|| ((() - 1) == 'n'
&& (() - 2) == 'a' && str
.charAt(() - 3) == 't')
|| ((() - 1) == 'g'
&& (() - 2) == 'o' && str
.charAt(() - 3) == 'l')) {
return 3;
} else if (((() - 1) == 'n' && (str
.length() - 2) == 'l')
|| ((() - 1) == '!' && (str
.length() - 2) == 'n')) {
return 2;
} else {
return 1;
}
}
/*
 * To determine whether a str is legal, the return value is true and false
 * Only 0123456789.()sincostanlnlogn!+-×÷√^ is a legal str, returns true
 * The str containing characters other than 0123456789.()sincostanlnlogn!+-×÷√^ is illegal, return false
 */
private boolean right(String str) {
int i = 0;
for (i = 0; i < (); i++) {
if ((i) != '0' && (i) != '1'
&& (i) != '2' && (i) != '3'
&& (i) != '4' && (i) != '5'
&& (i) != '6' && (i) != '7'
&& (i) != '8' && (i) != '9'
&& (i) != '.' && (i) != '-'
&& (i) != '+' && (i) != '×'
&& (i) != '÷' && (i) != '√'
&& (i) != '^' && (i) != 's'
&& (i) != 'i' && (i) != 'n'
&& (i) != 'c' && (i) != 'o'
&& (i) != 't' && (i) != 'a'
&& (i) != 'l' && (i) != 'g'
&& (i) != '(' && (i) != ')'
&& (i) != '!')
break;
}
if (i == ()) {
return true;
} else {
return false;
}
}
/*
 * The entire computing core,
 * Just pass the entire string of the expression into calc().process() to perform the calculation. The algorithm includes the following parts:
 * 1. Calculation part
 * process(String str) Of course, this is based on the situation of checking errors without errors
 * 2. Data formatting FP(double n) makes the data have considerable accuracy
 * 3. Factorial algorithm N(double n) calculates n! and returns the result
 * 4. Error prompt showError(int code,String str)
 * Return error
 */
public class calc {
public calc() {
}
final int MAXLEN = 500;
/*
 * Calculate the expression scan from left to right, the number is entered into the number stack, and the operator is entered into the operator stack
 * +-Basic priority is 1,
 * ×÷ The basic priority is 2,
 * log ln sin cos tan n! The basic priority is 3,
 * √^Basic priority is 4
 * The inner bracket operator is 4 higher than the outer synchronous operator
 * The current operator has higher priority than the stack top pressure stack.
 * A operator pops up below the top of the stack to operate with two numbers
 * Repeat until the current operator is greater than the top of the stack
 * After scanning, calculate the remaining operators and numbers in turn
 */
public void process(String str) {
int weightPlus = 0, topOp = 0, topNum = 0, flag = 1, weightTemp = 0;
// weightPlus is the basic priority under the same(), weightTemp temporarily records the change in priority// topOp is the counter of weight[], operator[]; topNum is the counter of number[]// Flag is a counter with positive and negative numbers, 1 is a positive number, -1 is a negative numberint weight[]; // Save the priority of operators in the operator stack and count with topOpdouble number[]; // Save the number and count with topNumchar ch, ch_gai, operator[];// operator[] saves operator, counts with topOpString num;// Record the number, str is divided into segments with +-×÷()sctgl!√^, and the string between the +-×÷()sctgl!√^ characters is the numberweight = 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 < ()) {
ch = (i);
//Judge positive and negative numbersif (i == 0) {
if (ch == '-')
flag = -1;
} else if ((i - 1) == '(' && ch == '-')
flag = -1;
// Get the number and transfer the positive and negative signs to the numberif (ch <= '9' && ch >= '0' || ch == '.' || ch == 'E') {
num = ();
ch_gai = ch;
("guojs", ch + "--->" + i);
// Get the entire numberwhile (i < ()
&& (ch_gai <= '9' && ch_gai >= '0' || ch_gai == '.' || ch_gai == 'E')) {
ch_gai = (i++);
("guojs", "The value of i is:" + i);
}
// Return the pointer to its previous positionif (i >= ())
i -= 1;
else {
i -= 2;
}
if ((".") == 0)
number[topNum++] = 0;
// Transfer positive and negative signs to numberselse {
number[topNum++] = (num) * flag;
flag = 1;
}
}
// Calculate the priority of the operatorif (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) {
// +-The lowest priority is 1case '+':
case '-':
weightTemp = 1 + weightPlus;
break;
// The priority of x÷ is slightly higher, 2case '×':
case '÷':
weightTemp = 2 + weightPlus;
break;
// Sincos and other priority is 3case 's':
case 'c':
case 't':
case 'g':
case 'l':
case '!':
weightTemp = 3 + weightPlus;
break;
// The remaining priority is 4// case '^':
// case '√':
default:
weightTemp = 4 + weightPlus;
break;
}
// If the current priority is greater than the top element of the stack, then directly enter the stackif (topOp == 0 || weight[topOp - 1] < weightTemp) {
weight[topOp] = weightTemp;
operator[topOp] = ch;
topOp++;
// Otherwise, remove the operators in the stack one by one until the priority of the operator on the top of the current stack is less than the current operator} else {
while (topOp > 0 && weight[topOp - 1] >= weightTemp) {
switch (operator[topOp - 1]) {
// Take out the corresponding elements of the numeric array for calculationcase '+':
number[topNum - 2] += number[topNum - 1];
break;
case '-':
number[topNum - 2] -= number[topNum - 1];
break;
case '×':
number[topNum - 2] *= number[topNum - 1];
break;
// Determine the situation where the divisor is 0case '÷':
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] = (
number[topNum - 2],
1 / number[topNum - 1]);
break;
case '^':
number[topNum - 2] = (
number[topNum - 2], number[topNum - 1]);
break;
// Measure and convert angle radians during calculation// 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 (((number[topNum - 1]) / 90) % 2 == 1) {
showError(2, str_old);
return;
}
number[topNum - 1] = Math
.tan((number[topNum - 1] / 180)
* pi);
} else {
if (((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;
// Factoriescase '!':
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;
}
// Continue to take the next element of the stack for judgmenttopNum--;
topOp--;
}
// Put operators as stackweight[topOp] = weightTemp;
operator[topOp] = ch;
topOp++;
}
}
i++;
}
// Take out the stack operators in turn for calculationwhile (topOp > 0) {
// +-x directly extracts the last two digits of the arrayswitch (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;
// When it comes to division, consider the situation where the divisor cannot be zerocase '÷':
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] = (number[topNum - 2],
1 / number[topNum - 1]);
break;
case '^':
number[topNum - 2] = (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] = (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] = (number[topNum - 1]);
}
topNum++;
break;
// tan
case 't':
if (drg_flag == true) {
if (((number[topNum - 1]) / 90) % 2 == 1) {
showError(2, str_old);
return;
}
number[topNum - 1] = Math
.tan((number[topNum - 1] / 180) * pi);
} else {
if (((number[topNum - 1]) / (pi / 2)) % 2 == 1) {
showError(2, str_old);
return;
}
number[topNum - 1] = (number[topNum - 1]);
}
topNum++;
break;
// Logarithmic logcase 'g':
if (number[topNum - 1] <= 0) {
showError(2, str_old);
return;
}
number[topNum - 1] = Math.log10(number[topNum - 1]);
topNum++;
break;
// Natural logarithm lncase 'l':
if (number[topNum - 1] <= 0) {
showError(2, str_old);
return;
}
number[topNum - 1] = (number[topNum - 1]);
topNum++;
break;
// Factoriescase '!':
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;
}
// Calculate the next element of the stacktopNum--;
topOp--;
}
// If the number is too large, an error message will be promptedif (number[0] > 7.3E306) {
showError(3, str_old);
return;
}
// Output the final result((FP(number[0])));
("The calculation is completed, if you want to continue, please press the zero key C");
(str_old + "=" + (FP(number[0])));
}
/*
 * FP = floating point Controls the number of decimal places to achieve accuracy otherwise it will appear
 * The situation where 0.6-0.2=0.3999999999999999997 can be solved with FP, so that the number is 0.4 The accuracy of this format is 15 bits.
 */
public double FP(double n) {
// NumberFormat format=(); // Create a formatted class f// (18); // Set the format of decimal placesDecimalFormat format = new DecimalFormat("0.#############");
return ((n));
}
/*
 * Factorial algorithm
 */
public double N(double n) {
int i = 0;
double sum = 1;
// Multiply the values ​​less than or equal to n in turnfor (i = 1; i <= n; i++) {
sum = sum * i;
}
return sum;
}
/*
 * Error prompt, after pressing "=", if an error occurs during the process() process, a prompt will be made.
 */
public void showError(int code, String str) {
String message = "";
switch (code) {
case 1:
message = "Zero cannot be a divisor";
break;
case 2:
message = "Function format error";
break;
case 3:
message = "The value is too large, out of range";
}
("\"" + str + "\"" + ": " + message);
(message + "\n" + "The calculation is completed, if you want to continue, please press the zero key C");
}
}
}

menu_main.xml

<menu xmlns:andro >
<item
android:
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_settings"/>
</menu>

The above code is the calculator code for Java implementation Android with brackets introduced to you. Where is the code not written well? Please give me more valuable suggestions. The editor will contact you in time. Also, thank you very much for your support for my website.