diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a881469 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.gradle +/local.properties +/.idea +.DS_Store +/build +/captures diff --git a/README.md b/README.md index a94d6b4..7118c2a 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,31 @@ -# calculator -Submit your calculator projects here +## scientific-calculator +https://github.com/accesscode-2-1/unit-1/blob/master/project/requirements.md + +## Code Structure + +**Back-End** +> Using [Udo klimaschewski's EvalEx](https://github.com/uklimaschewski/EvalEx) repo on Java Expression parsing, the calculator is able to take in a String equation and evaluate the mathematical answer returned in BigDecimal. For operations that EvalEx does not handle, we wrote our own methods in Numbers.java. MainActivity.java contains all Button Listener instructions, separated in half by basic calculator buttons on top and scientific calculator functions below. We decided to use only Buttons and Textviews to limit the possibility of invalid user input. We kept two separate variables for the equation to be parsed and the display equation the user sees, as the string format for parsing is not always user friendly. + +**Layout** +> The calculator's UI is comprised of a series of nested linear (weighted) and relative layouts, TextViews, and Buttons. To deal with several separate elements, we chose to keep the UI as "open" as possible—buttons and display are borderless with little embellishment, color palette very minimal. Visual attributes of the buttons are assigned/managed using one style. Button's onclick appearance was also customized to provide greater visual feedback on touch. + +> Our layout utilizes two TextViews: one to display result and another to track the current equation. TextViews are limited to one line in order to avoid breaking the layout with long results or equations. + +> When confronted with interface/user experience issues, we found that implementing a HorizontalScrollView enabled us to display equations exceeding layout boundaries, while the ToggleButton widget helped circumvent the issue of a crowded interface/inefficient use of space. Layout code was mainly handled by Jae with input, debugging, and modifications contributed by Sufei. + +**Challenges** +* Inaccuracies with sin/cos implementation. We researched the Taylor Series but it proved too complex, opted for a simpler approach. +* Keeping track of several factors simultaneously, elegantly handling special cases, reconfiguring logic. +* Making up for library deficiencies. +* Maintaining consistency and utility in UI across devices. +* Constant debugging! + +**Issues** +* +/- button implements incorrectly for certain inputs (^, Ans). +* Backspace + +**Improvements** +* Given more time, we would have loved to complete the Wolfram Alpha API and graphing bonuses. +* Would have loved to explore Material design and animations. +* Re-evaluate logic that needs to be continuously readjusted. +* Clean up MainActivity. diff --git a/ScientificCalculator/.gitignore b/ScientificCalculator/.gitignore new file mode 100644 index 0000000..afbdab3 --- /dev/null +++ b/ScientificCalculator/.gitignore @@ -0,0 +1,6 @@ +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +.DS_Store +/build diff --git a/ScientificCalculator/.idea/.name b/ScientificCalculator/.idea/.name new file mode 100644 index 0000000..883c721 --- /dev/null +++ b/ScientificCalculator/.idea/.name @@ -0,0 +1 @@ +ScientificCalculator \ No newline at end of file diff --git a/ScientificCalculator/.idea/compiler.xml b/ScientificCalculator/.idea/compiler.xml new file mode 100644 index 0000000..217af47 --- /dev/null +++ b/ScientificCalculator/.idea/compiler.xml @@ -0,0 +1,23 @@ + + + + + + diff --git a/ScientificCalculator/.idea/copyright/profiles_settings.xml b/ScientificCalculator/.idea/copyright/profiles_settings.xml new file mode 100644 index 0000000..e7bedf3 --- /dev/null +++ b/ScientificCalculator/.idea/copyright/profiles_settings.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/ScientificCalculator/.idea/encodings.xml b/ScientificCalculator/.idea/encodings.xml new file mode 100644 index 0000000..e206d70 --- /dev/null +++ b/ScientificCalculator/.idea/encodings.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/ScientificCalculator/.idea/gradle.xml b/ScientificCalculator/.idea/gradle.xml new file mode 100644 index 0000000..fe865d3 --- /dev/null +++ b/ScientificCalculator/.idea/gradle.xml @@ -0,0 +1,19 @@ + + + + + + + diff --git a/ScientificCalculator/.idea/misc.xml b/ScientificCalculator/.idea/misc.xml new file mode 100644 index 0000000..59436c9 --- /dev/null +++ b/ScientificCalculator/.idea/misc.xml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/ScientificCalculator/.idea/modules.xml b/ScientificCalculator/.idea/modules.xml new file mode 100644 index 0000000..e35acaf --- /dev/null +++ b/ScientificCalculator/.idea/modules.xml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/ScientificCalculator/.idea/scopes/scope_settings.xml b/ScientificCalculator/.idea/scopes/scope_settings.xml new file mode 100644 index 0000000..922003b --- /dev/null +++ b/ScientificCalculator/.idea/scopes/scope_settings.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/ScientificCalculator/.idea/vcs.xml b/ScientificCalculator/.idea/vcs.xml new file mode 100644 index 0000000..def6a6a --- /dev/null +++ b/ScientificCalculator/.idea/vcs.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/ScientificCalculator/ScientificCalculator.iml b/ScientificCalculator/ScientificCalculator.iml new file mode 100644 index 0000000..0bb6048 --- /dev/null +++ b/ScientificCalculator/ScientificCalculator.iml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + diff --git a/ScientificCalculator/app/.gitignore b/ScientificCalculator/app/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/ScientificCalculator/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/ScientificCalculator/app/app.iml b/ScientificCalculator/app/app.iml new file mode 100644 index 0000000..078bbeb --- /dev/null +++ b/ScientificCalculator/app/app.iml @@ -0,0 +1,93 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ScientificCalculator/app/build.gradle b/ScientificCalculator/app/build.gradle new file mode 100644 index 0000000..32762ff --- /dev/null +++ b/ScientificCalculator/app/build.gradle @@ -0,0 +1,25 @@ +apply plugin: 'com.android.application' + +android { + compileSdkVersion 22 + buildToolsVersion "22.0.1" + + defaultConfig { + applicationId "nyc.c4q.sufeiiz.scientificcalculator" + minSdkVersion 15 + targetSdkVersion 22 + versionCode 1 + versionName "1.0" + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + compile fileTree(dir: 'libs', include: ['*.jar']) + compile 'com.android.support:appcompat-v7:22.1.1' +} diff --git a/ScientificCalculator/app/proguard-rules.pro b/ScientificCalculator/app/proguard-rules.pro new file mode 100644 index 0000000..39ee882 --- /dev/null +++ b/ScientificCalculator/app/proguard-rules.pro @@ -0,0 +1,17 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in /Users/sufeizhao/Library/Android/sdk/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} diff --git a/ScientificCalculator/app/src/androidTest/java/nyc/c4q/sufeiiz/scientificcalculator/ApplicationTest.java b/ScientificCalculator/app/src/androidTest/java/nyc/c4q/sufeiiz/scientificcalculator/ApplicationTest.java new file mode 100644 index 0000000..2380304 --- /dev/null +++ b/ScientificCalculator/app/src/androidTest/java/nyc/c4q/sufeiiz/scientificcalculator/ApplicationTest.java @@ -0,0 +1,13 @@ +package nyc.c4q.sufeiiz.scientificcalculator; + +import android.app.Application; +import android.test.ApplicationTestCase; + +/** + * Testing Fundamentals + */ +public class ApplicationTest extends ApplicationTestCase { + public ApplicationTest() { + super(Application.class); + } +} \ No newline at end of file diff --git a/ScientificCalculator/app/src/main/AndroidManifest.xml b/ScientificCalculator/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..08814a1 --- /dev/null +++ b/ScientificCalculator/app/src/main/AndroidManifest.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + diff --git a/ScientificCalculator/app/src/main/ic_launcher-web.png b/ScientificCalculator/app/src/main/ic_launcher-web.png new file mode 100644 index 0000000..25d6276 Binary files /dev/null and b/ScientificCalculator/app/src/main/ic_launcher-web.png differ diff --git a/ScientificCalculator/app/src/main/java/nyc/c4q/sufeiiz/scientificcalculator/Expression.java b/ScientificCalculator/app/src/main/java/nyc/c4q/sufeiiz/scientificcalculator/Expression.java new file mode 100644 index 0000000..a41ab94 --- /dev/null +++ b/ScientificCalculator/app/src/main/java/nyc/c4q/sufeiiz/scientificcalculator/Expression.java @@ -0,0 +1,1100 @@ +package nyc.c4q.sufeiiz.scientificcalculator; + +/* + * Copyright 2012 Udo Klimaschewski + * + * http://UdoJava.com/ + * http://about.me/udo.klimaschewski + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.MathContext; +import java.math.RoundingMode; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Stack; + +/** + *

EvalEx - Java Expression Evaluator

+ * + *

Introduction

+ * EvalEx is a handy expression evaluator for Java, that allows to evaluate simple mathematical and boolean expressions. + *
+ * Key Features: + * + *
+ *

Examples

+ *
+ *  BigDecimal result = null;
+ *
+ *  Expression expression = new Expression("1+1/3");
+ *  result = expression.eval():
+ *  expression.setPrecision(2);
+ *  result = expression.eval():
+ *
+ *  result = new Expression("(3.4 + -4.1)/2").eval();
+ *
+ *  result = new Expression("SQRT(a^2 + b^2").with("a","2.4").and("b","9.253").eval();
+ *
+ *  BigDecimal a = new BigDecimal("2.4");
+ *  BigDecimal b = new BigDecimal("9.235");
+ *  result = new Expression("SQRT(a^2 + b^2").with("a",a).and("b",b).eval();
+ *
+ *  result = new Expression("2.4/PI").setPrecision(128).setRoundingMode(RoundingMode.UP).eval();
+ *
+ *  result = new Expression("random() > 0.5").eval();
+ *
+ *  result = new Expression("not(x<7 || sqrt(max(x,9)) <= 3))").with("x","22.9").eval();
+ * 
+ *
+ *

Supported Operators

+ * + * + * + * + * + * + * + * + * + *
Mathematical Operators
OperatorDescription
+Additive operator
-Subtraction operator
*Multiplication operator
/Division operator
%Remainder operator (Modulo)
^Power operator
+ *
+ * + * + * + * + * + * + * + * + * + * + * + * + * + *
Boolean Operators*
OperatorDescription
=Equals
==Equals
!=Not equals
<>Not equals
<Less than
<=Less than or equal to
>Greater than
>=Greater than or equal to
&&Boolean and
||Boolean or
+ * *Boolean operators result always in a BigDecimal value of 1 or 0 (zero). Any non-zero value is treated as a _true_ value. Boolean _not_ is implemented by a function. + *
+ *

Supported Functions

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Function*Description
NOT(expression)Boolean negation, 1 (means true) if the expression is not zero
IF(condition,value_if_true,value_if_false)Returns one value if the condition evaluates to true or the other if it evaluates to false
RANDOM()Produces a random number between 0 and 1
MIN(e1,e2)Returns the smaller of both expressions
MAX(e1,e2)Returns the bigger of both expressions
ABS(expression)Returns the absolute (non-negative) value of the expression
ROUND(expression,precision)Rounds a value to a certain number of digits, uses the current rounding mode
FLOOR(expression)Rounds the value down to the nearest integer
CEILING(expression)Rounds the value up to the nearest integer
LOG(expression)Returns the natural logarithm (base e) of an expression
LOG10(expression)Returns the common logarithm (base 10) of an expression
SQRT(expression)Returns the square root of an expression
SIN(expression)Returns the trigonometric sine of an angle (in degrees)
COS(expression)Returns the trigonometric cosine of an angle (in degrees)
TAN(expression)Returns the trigonometric tangens of an angle (in degrees)
SINH(expression)Returns the hyperbolic sine of a value
COSH(expression)Returns the hyperbolic cosine of a value
TANH(expression)Returns the hyperbolic tangens of a value
RAD(expression)Converts an angle measured in degrees to an approximately equivalent angle measured in radians
DEG(expression)Converts an angle measured in radians to an approximately equivalent angle measured in degrees
+ * *Functions names are case insensitive. + *
+ *

Supported Constants

+ * + * + * + * + * + *
ConstantDescription
PIThe value of PI, exact to 100 digits
TRUEThe value one
FALSEThe value zero
+ * + *

Add Custom Operators

+ * + * Custom operators can be added easily, simply create an instance of `Expression.Operator` and add it to the expression. + * Parameters are the operator string, its precedence and if it is left associative. The operators `eval()` method will be called with the BigDecimal values of the operands. + * All existing operators can also be overridden. + *
+ * For example, add an operator `x >> n`, that moves the decimal point of _x_ _n_ digits to the right: + * + *
+ * Expression e = new Expression("2.1234 >> 2");
+ *
+ * e.addOperator(e.new Operator(">>", 30, true) {
+ *     {@literal @}Override
+ *     public BigDecimal eval(BigDecimal v1, BigDecimal v2) {
+ *         return v1.movePointRight(v2.toBigInteger().intValue());
+ *     }
+ * });
+ *
+ * e.eval(); // returns 212.34
+ * 
+ *
+ *

Add Custom Functions

+ * + * Adding custom functions is as easy as adding custom operators. Create an instance of `Expression.Function`and add it to the expression. + * Parameters are the function name and the count of required parameters. The functions `eval()` method will be called with a list of the BigDecimal parameters. + * All existing functions can also be overridden. + *
+ * For example, add a function `average(a,b,c)`, that will calculate the average value of a, b and c: + *
+ *
+ * Expression e = new Expression("2 * average(12,4,8)");
+ *
+ * e.addFunction(e.new Function("average", 3) {
+ *     {@literal @}Override
+ *     public BigDecimal eval(List parameters) {
+ *         BigDecimal sum = parameters.get(0).add(parameters.get(1)).add(parameters.get(2));
+ *         return sum.divide(new BigDecimal(3));
+ *     }
+ * });
+ *
+ * e.eval(); // returns 16
+ * 
+ * The software is licensed under the MIT Open Source license (see LICENSE file). + *
+ * + * + *@author Udo Klimaschewski (http://about.me/udo.klimaschewski) + */ +public class Expression { + + /** + * Definition of PI as a constant, can be used in expressions as variable. + */ + public static final BigDecimal PI = new BigDecimal( + "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679"); + + /** + * The {@link java.math.MathContext} to use for calculations. + */ + private MathContext mc = MathContext.DECIMAL32; + + /** + * The original infix expression. + */ + private String expression = null; + + /** + * The cached RPN (Reverse Polish Notation) of the expression. + */ + private List rpn = null; + + /** + * All defined operators with name and implementation. + */ + private Map operators = new HashMap(); + + /** + * All defined functions with name and implementation. + */ + private Map functions = new HashMap(); + + /** + * All defined variables with name and value. + */ + private Map variables = new HashMap(); + + /** + * What character to use for decimal separators. + */ + private final char decimalSeparator = '.'; + + /** + * What character to use for minus sign (negative values). + */ + private final char minusSign = '-'; + + /** + * The expression evaluators exception class. + */ + public class ExpressionException extends RuntimeException { + private static final long serialVersionUID = 1118142866870779047L; + + public ExpressionException(String message) { + super(message); + } + } + + /** + * Abstract definition of a supported expression function. A function is + * defined by a name, the number of parameters and the actual processing + * implementation. + */ + public abstract class Function { + /** + * Name of this function. + */ + private String name; + /** + * Number of parameters expected for this function. + */ + private int numParams; + + /** + * Creates a new function with given name and parameter count. + * + * @param name + * The name of the function. + * @param numParams + * The number of parameters for this function. + */ + public Function(String name, int numParams) { + this.name = name.toUpperCase(); + this.numParams = numParams; + } + + public String getName() { + return name; + } + + public int getNumParams() { + return numParams; + } + + /** + * Implementation for this function. + * + * @param parameters + * Parameters will be passed by the expression evaluator as a + * {@link List} of {@link BigDecimal} values. + * @return The function must return a new {@link BigDecimal} value as a + * computing result. + */ + public abstract BigDecimal eval(List parameters); + } + + /** + * Abstract definition of a supported operator. An operator is defined by + * its name (pattern), precedence and if it is left- or right associative. + */ + public abstract class Operator { + /** + * This operators name (pattern). + */ + private String oper; + /** + * Operators precedence. + */ + private int precedence; + /** + * Operator is left associative. + */ + private boolean leftAssoc; + + /** + * Creates a new operator. + * + * @param oper + * The operator name (pattern). + * @param precedence + * The operators precedence. + * @param leftAssoc + * true if the operator is left associative, + * else false. + */ + public Operator(String oper, int precedence, boolean leftAssoc) { + this.oper = oper; + this.precedence = precedence; + this.leftAssoc = leftAssoc; + } + + public String getOper() { + return oper; + } + + public int getPrecedence() { + return precedence; + } + + public boolean isLeftAssoc() { + return leftAssoc; + } + + /** + * Implementation for this operator. + * + * @param v1 + * Operand 1. + * @param v2 + * Operand 2. + * @return The result of the operation. + */ + public abstract BigDecimal eval(BigDecimal v1, BigDecimal v2); + } + + /** + * Expression tokenizer that allows to iterate over a {@link String} + * expression token by token. Blank characters will be skipped. + */ + private class Tokenizer implements Iterator { + + /** + * Actual position in expression string. + */ + private int pos = 0; + + /** + * The original input expression. + */ + private String input; + /** + * The previous token or null if none. + */ + private String previousToken; + + /** + * Creates a new tokenizer for an expression. + * + * @param input + * The expression string. + */ + public Tokenizer(String input) { + this.input = input.trim(); + } + + @Override + public boolean hasNext() { + return (pos < input.length()); + } + + /** + * Peek at the next character, without advancing the iterator. + * + * @return The next character or character 0, if at end of string. + */ + private char peekNextChar() { + if (pos < (input.length() - 1)) { + return input.charAt(pos + 1); + } else { + return 0; + } + } + + @Override + public String next() { + StringBuilder token = new StringBuilder(); + if (pos >= input.length()) { + return previousToken = null; + } + char ch = input.charAt(pos); + while (Character.isWhitespace(ch) && pos < input.length()) { + ch = input.charAt(++pos); + } + if (Character.isDigit(ch)) { + while ((Character.isDigit(ch) || ch == decimalSeparator) + && (pos < input.length())) { + token.append(input.charAt(pos++)); + ch = pos == input.length() ? 0 : input.charAt(pos); + } + } else if (ch == minusSign + && Character.isDigit(peekNextChar()) + && ("(".equals(previousToken) || ",".equals(previousToken) + || previousToken == null || operators + .containsKey(previousToken))) { + token.append(minusSign); + pos++; + token.append(next()); + } else if (Character.isLetter(ch) || (ch == '_')) { + while ((Character.isLetter(ch) || Character.isDigit(ch) || (ch == '_')) && (pos < input.length())) { + token.append(input.charAt(pos++)); + ch = pos == input.length() ? 0 : input.charAt(pos); + } + } else if (ch == '(' || ch == ')' || ch == ',') { + token.append(ch); + pos++; + } else { + while (!Character.isLetter(ch) && !Character.isDigit(ch) && ch != '_' + && !Character.isWhitespace(ch) && ch != '(' + && ch != ')' && ch != ',' && (pos < input.length())) { + token.append(input.charAt(pos)); + pos++; + ch = pos == input.length() ? 0 : input.charAt(pos); + if (ch == minusSign) { + break; + } + } + if (!operators.containsKey(token.toString())) { + throw new ExpressionException("Unknown operator '" + token + + "' at position " + (pos - token.length() + 1)); + } + } + return previousToken = token.toString(); + } + + @Override + public void remove() { + throw new ExpressionException("remove() not supported"); + } + + /** + * Get the actual character position in the string. + * + * @return The actual character position. + */ + public int getPos() { + return pos; + } + + } + + /** + * Creates a new expression instance from an expression string. + * + * @param expression + * The expression. E.g. "2.4*sin(3)/(2-4)" or + * "sin(y)>0 & max(z, 3)>3" + */ + public Expression(String expression) { + this.expression = expression; + addOperator(new Operator("+", 20, true) { + @Override + public BigDecimal eval(BigDecimal v1, BigDecimal v2) { + return v1.add(v2, mc); + } + }); + addOperator(new Operator("-", 20, true) { + @Override + public BigDecimal eval(BigDecimal v1, BigDecimal v2) { + return v1.subtract(v2, mc); + } + }); + addOperator(new Operator("*", 30, true) { + @Override + public BigDecimal eval(BigDecimal v1, BigDecimal v2) { + return v1.multiply(v2, mc); + } + }); + addOperator(new Operator("/", 30, true) { + @Override + public BigDecimal eval(BigDecimal v1, BigDecimal v2) { + return v1.divide(v2, mc); + } + }); + addOperator(new Operator("%", 30, true) { + @Override + public BigDecimal eval(BigDecimal v1, BigDecimal v2) { + return v1.remainder(v2, mc); + } + }); + addOperator(new Operator("^", 40, false) { + @Override + public BigDecimal eval(BigDecimal v1, BigDecimal v2) { + /*- + * Thanks to Gene Marin: + * http://stackoverflow.com/questions/3579779/how-to-do-a-fractional-power-on-bigdecimal-in-java + */ + int signOf2 = v2.signum(); + double dn1 = v1.doubleValue(); + v2 = v2.multiply(new BigDecimal(signOf2)); // n2 is now positive + BigDecimal remainderOf2 = v2.remainder(BigDecimal.ONE); + BigDecimal n2IntPart = v2.subtract(remainderOf2); + BigDecimal intPow = v1.pow(n2IntPart.intValueExact(), mc); + BigDecimal doublePow = new BigDecimal(Math.pow(dn1, + remainderOf2.doubleValue())); + + BigDecimal result = intPow.multiply(doublePow, mc); + if (signOf2 == -1) { + result = BigDecimal.ONE.divide(result, mc.getPrecision(), + RoundingMode.HALF_UP); + } + return result; + } + }); + addOperator(new Operator("&&", 4, false) { + @Override + public BigDecimal eval(BigDecimal v1, BigDecimal v2) { + boolean b1 = !v1.equals(BigDecimal.ZERO); + boolean b2 = !v2.equals(BigDecimal.ZERO); + return b1 && b2 ? BigDecimal.ONE : BigDecimal.ZERO; + } + }); + + addOperator(new Operator("||", 2, false) { + @Override + public BigDecimal eval(BigDecimal v1, BigDecimal v2) { + boolean b1 = !v1.equals(BigDecimal.ZERO); + boolean b2 = !v2.equals(BigDecimal.ZERO); + return b1 || b2 ? BigDecimal.ONE : BigDecimal.ZERO; + } + }); + + addOperator(new Operator(">", 10, false) { + @Override + public BigDecimal eval(BigDecimal v1, BigDecimal v2) { + return v1.compareTo(v2) == 1 ? BigDecimal.ONE : BigDecimal.ZERO; + } + }); + + addOperator(new Operator(">=", 10, false) { + @Override + public BigDecimal eval(BigDecimal v1, BigDecimal v2) { + return v1.compareTo(v2) >= 0 ? BigDecimal.ONE : BigDecimal.ZERO; + } + }); + + addOperator(new Operator("<", 10, false) { + @Override + public BigDecimal eval(BigDecimal v1, BigDecimal v2) { + return v1.compareTo(v2) == -1 ? BigDecimal.ONE + : BigDecimal.ZERO; + } + }); + + addOperator(new Operator("<=", 10, false) { + @Override + public BigDecimal eval(BigDecimal v1, BigDecimal v2) { + return v1.compareTo(v2) <= 0 ? BigDecimal.ONE : BigDecimal.ZERO; + } + }); + + addOperator(new Operator("=", 7, false) { + @Override + public BigDecimal eval(BigDecimal v1, BigDecimal v2) { + return v1.compareTo(v2) == 0 ? BigDecimal.ONE : BigDecimal.ZERO; + } + }); + addOperator(new Operator("==", 7, false) { + @Override + public BigDecimal eval(BigDecimal v1, BigDecimal v2) { + return operators.get("=").eval(v1, v2); + } + }); + + addOperator(new Operator("!=", 7, false) { + @Override + public BigDecimal eval(BigDecimal v1, BigDecimal v2) { + return v1.compareTo(v2) != 0 ? BigDecimal.ONE : BigDecimal.ZERO; + } + }); + addOperator(new Operator("<>", 7, false) { + @Override + public BigDecimal eval(BigDecimal v1, BigDecimal v2) { + return operators.get("!=").eval(v1, v2); + } + }); + + addFunction(new Function("NOT", 1) { + @Override + public BigDecimal eval(List parameters) { + boolean zero = parameters.get(0).compareTo(BigDecimal.ZERO) == 0; + return zero ? BigDecimal.ONE : BigDecimal.ZERO; + } + }); + + addFunction(new Function("IF", 3) { + @Override + public BigDecimal eval(List parameters) { + boolean isTrue = !parameters.get(0).equals(BigDecimal.ZERO); + return isTrue ? parameters.get(1) : parameters.get(2); + } + }); + + addFunction(new Function("RANDOM", 0) { + @Override + public BigDecimal eval(List parameters) { + double d = Math.random(); + return new BigDecimal(d, mc); + } + }); + addFunction(new Function("SIN", 1) { + @Override + public BigDecimal eval(List parameters) { + double d = Math.sin(Math.toRadians(parameters.get(0) + .doubleValue())); + return new BigDecimal(d, mc); + } + }); + addFunction(new Function("COS", 1) { + @Override + public BigDecimal eval(List parameters) { + double d = Math.cos(Math.toRadians(parameters.get(0) + .doubleValue())); + return new BigDecimal(d, mc); + } + }); + addFunction(new Function("TAN", 1) { + @Override + public BigDecimal eval(List parameters) { + double d = Math.tan(Math.toRadians(parameters.get(0) + .doubleValue())); + return new BigDecimal(d, mc); + } + }); + addFunction(new Function("SINH", 1) { + @Override + public BigDecimal eval(List parameters) { + double d = Math.sinh(parameters.get(0).doubleValue()); + return new BigDecimal(d, mc); + } + }); + addFunction(new Function("COSH", 1) { + @Override + public BigDecimal eval(List parameters) { + double d = Math.cosh(parameters.get(0).doubleValue()); + return new BigDecimal(d, mc); + } + }); + addFunction(new Function("TANH", 1) { + @Override + public BigDecimal eval(List parameters) { + double d = Math.tanh(parameters.get(0).doubleValue()); + return new BigDecimal(d, mc); + } + }); + addFunction(new Function("RAD", 1) { + @Override + public BigDecimal eval(List parameters) { + double d = Math.toRadians(parameters.get(0).doubleValue()); + return new BigDecimal(d, mc); + } + }); + addFunction(new Function("DEG", 1) { + @Override + public BigDecimal eval(List parameters) { + double d = Math.toDegrees(parameters.get(0).doubleValue()); + return new BigDecimal(d, mc); + } + }); + addFunction(new Function("MAX", 2) { + @Override + public BigDecimal eval(List parameters) { + BigDecimal v1 = parameters.get(0); + BigDecimal v2 = parameters.get(1); + return v1.compareTo(v2) > 0 ? v1 : v2; + } + }); + addFunction(new Function("MIN", 2) { + @Override + public BigDecimal eval(List parameters) { + BigDecimal v1 = parameters.get(0); + BigDecimal v2 = parameters.get(1); + return v1.compareTo(v2) < 0 ? v1 : v2; + } + }); + addFunction(new Function("ABS", 1) { + @Override + public BigDecimal eval(List parameters) { + return parameters.get(0).abs(mc); + } + }); + addFunction(new Function("LOG", 1) { + @Override + public BigDecimal eval(List parameters) { + double d = Math.log(parameters.get(0).doubleValue()); + return new BigDecimal(d, mc); + } + }); + addFunction(new Function("LOG10", 1) { + @Override + public BigDecimal eval(List parameters) { + double d = Math.log10(parameters.get(0).doubleValue()); + return new BigDecimal(d, mc); + } + }); + addFunction(new Function("ROUND", 2) { + @Override + public BigDecimal eval(List parameters) { + BigDecimal toRound = parameters.get(0); + int precision = parameters.get(1).intValue(); + return toRound.setScale(precision, mc.getRoundingMode()); + } + }); + addFunction(new Function("FLOOR", 1) { + @Override + public BigDecimal eval(List parameters) { + BigDecimal toRound = parameters.get(0); + return toRound.setScale(0, RoundingMode.FLOOR); + } + }); + addFunction(new Function("CEILING", 1) { + @Override + public BigDecimal eval(List parameters) { + BigDecimal toRound = parameters.get(0); + return toRound.setScale(0, RoundingMode.CEILING); + } + }); + addFunction(new Function("SQRT", 1) { + @Override + public BigDecimal eval(List parameters) { + /* + * From The Java Programmers Guide To numerical Computing + * (Ronald Mak, 2003) + */ + BigDecimal x = parameters.get(0); + if (x.compareTo(BigDecimal.ZERO) == 0) { + return new BigDecimal(0); + } + if (x.signum() < 0) { + throw new ExpressionException( + "Argument to SQRT() function must not be negative"); + } + BigInteger n = x.movePointRight(mc.getPrecision() << 1) + .toBigInteger(); + + int bits = (n.bitLength() + 1) >> 1; + BigInteger ix = n.shiftRight(bits); + BigInteger ixPrev; + + do { + ixPrev = ix; + ix = ix.add(n.divide(ix)).shiftRight(1); + // Give other threads a chance to work; + Thread.yield(); + } while (ix.compareTo(ixPrev) != 0); + + return new BigDecimal(ix, mc.getPrecision()); + } + }); + + variables.put("PI", PI); + variables.put("TRUE", BigDecimal.ONE); + variables.put("FALSE", BigDecimal.ZERO); + + } + + /** + * Is the string a number? + * + * @param st + * The string. + * @return true, if the input string is a number. + */ + private boolean isNumber(String st) { + if (st.charAt(0) == minusSign && st.length() == 1) + return false; + for (char ch : st.toCharArray()) { + if (!Character.isDigit(ch) && ch != minusSign + && ch != decimalSeparator) + return false; + } + return true; + } + + /** + * Implementation of the Shunting Yard algorithm to transform an + * infix expression to a RPN expression. + * + * @param expression + * The input expression in infx. + * @return A RPN representation of the expression, with each token as a list + * member. + */ + private List shuntingYard(String expression) { + List outputQueue = new ArrayList(); + Stack stack = new Stack(); + + Tokenizer tokenizer = new Tokenizer(expression); + + String lastFunction = null; + String previousToken = null; + while (tokenizer.hasNext()) { + String token = tokenizer.next(); + if (isNumber(token)) { + outputQueue.add(token); + } else if (variables.containsKey(token)) { + outputQueue.add(token); + } else if (functions.containsKey(token.toUpperCase())) { + stack.push(token); + lastFunction = token; + } else if (Character.isLetter(token.charAt(0))) { + stack.push(token); + } else if (",".equals(token)) { + while (!stack.isEmpty() && !"(".equals(stack.peek())) { + outputQueue.add(stack.pop()); + } + if (stack.isEmpty()) { + throw new ExpressionException("Parse error for function '" + + lastFunction + "'"); + } + } else if (operators.containsKey(token)) { + Operator o1 = operators.get(token); + String token2 = stack.isEmpty() ? null : stack.peek(); + while (operators.containsKey(token2) + && ((o1.isLeftAssoc() && o1.getPrecedence() <= operators + .get(token2).getPrecedence()) || (o1 + .getPrecedence() < operators.get(token2) + .getPrecedence()))) { + outputQueue.add(stack.pop()); + token2 = stack.isEmpty() ? null : stack.peek(); + } + stack.push(token); + } else if ("(".equals(token)) { + if (previousToken != null) { + if (isNumber(previousToken)) { + throw new ExpressionException("Missing operator at character position " + tokenizer.getPos()); + } + } + stack.push(token); + } else if (")".equals(token)) { + while (!stack.isEmpty() && !"(".equals(stack.peek())) { + outputQueue.add(stack.pop()); + } + if (stack.isEmpty()) { + throw new RuntimeException("Mismatched parentheses"); + } + stack.pop(); + if (!stack.isEmpty() + && functions.containsKey(stack.peek().toUpperCase())) { + outputQueue.add(stack.pop()); + } + } + previousToken = token; + } + while (!stack.isEmpty()) { + String element = stack.pop(); + if ("(".equals(element) || ")".equals(element)) { + throw new RuntimeException("Mismatched parentheses"); + } + if (!operators.containsKey(element)) { + throw new RuntimeException("Unknown operator or function: " + + element); + } + outputQueue.add(element); + } + return outputQueue; + } + + /** + * Evaluates the expression. + * + * @return The result of the expression. + */ + public BigDecimal eval() { + + Stack stack = new Stack(); + + for (String token : getRPN()) { + if (operators.containsKey(token)) { + BigDecimal v1 = stack.pop(); + BigDecimal v2 = stack.pop(); + stack.push(operators.get(token).eval(v2, v1)); + } else if (variables.containsKey(token)) { + stack.push(variables.get(token).round(mc)); + } else if (functions.containsKey(token.toUpperCase())) { + Function f = functions.get(token.toUpperCase()); + ArrayList p = new ArrayList( + f.getNumParams()); + for (int i = 0; i < f.numParams; i++) { + p.add(0,stack.pop()); + } + BigDecimal fResult = f.eval(p); + stack.push(fResult); + } else { + stack.push(new BigDecimal(token, mc)); + } + } + return stack.pop().stripTrailingZeros(); + } + + /** + * Sets the precision for expression evaluation. + * + * @param precision + * The new precision. + * + * @return The expression, allows to chain methods. + */ + public Expression setPrecision(int precision) { + this.mc = new MathContext(precision); + return this; + } + + /** + * Sets the rounding mode for expression evaluation. + * + * @param roundingMode + * The new rounding mode. + * @return The expression, allows to chain methods. + */ + public Expression setRoundingMode(RoundingMode roundingMode) { + this.mc = new MathContext(mc.getPrecision(), roundingMode); + return this; + } + + /** + * Adds an operator to the list of supported operators. + * + * @param operator + * The operator to add. + * @return The previous operator with that name, or null if + * there was none. + */ + public Operator addOperator(Operator operator) { + return operators.put(operator.getOper(), operator); + } + + /** + * Adds a function to the list of supported functions + * + * @param function + * The function to add. + * @return The previous operator with that name, or null if + * there was none. + */ + public Function addFunction(Function function) { + return functions.put(function.getName(), function); + } + + /** + * Sets a variable value. + * + * @param variable + * The variable name. + * @param value + * The variable value. + * @return The expression, allows to chain methods. + */ + public Expression setVariable(String variable, BigDecimal value) { + variables.put(variable, value); + return this; + } + + /** + * Sets a variable value. + * + * @param variable + * The variable to set. + * @param value + * The variable value. + * @return The expression, allows to chain methods. + */ + public Expression setVariable(String variable, String value) { + if (isNumber(value)) + variables.put(variable, new BigDecimal(value)); + else { + expression = expression.replaceAll("\\b" + variable + "\\b", "(" + value + ")"); + rpn = null; + } + return this; + } + + /** + * Sets a variable value. + * + * @param variable + * The variable to set. + * @param value + * The variable value. + * @return The expression, allows to chain methods. + */ + public Expression with(String variable, BigDecimal value) { + return setVariable(variable, value); + } + + /** + * Sets a variable value. + * + * @param variable + * The variable to set. + * @param value + * The variable value. + * @return The expression, allows to chain methods. + */ + public Expression and(String variable, String value) { + return setVariable(variable, value); + } + + /** + * Sets a variable value. + * + * @param variable + * The variable to set. + * @param value + * The variable value. + * @return The expression, allows to chain methods. + */ + public Expression and(String variable, BigDecimal value) { + return setVariable(variable, value); + } + + /** + * Sets a variable value. + * + * @param variable + * The variable to set. + * @param value + * The variable value. + * @return The expression, allows to chain methods. + */ + public Expression with(String variable, String value) { + return setVariable(variable, value); + } + + /** + * Get an iterator for this expression, allows iterating over an expression + * token by token. + * + * @return A new iterator instance for this expression. + */ + public Iterator getExpressionTokenizer() { + return new Tokenizer(this.expression); + } + + /** + * Cached access to the RPN notation of this expression, ensures only one + * calculation of the RPN per expression instance. If no cached instance + * exists, a new one will be created and put to the cache. + * + * @return The cached RPN instance. + */ + private List getRPN() { + if (rpn == null) { + rpn = shuntingYard(this.expression); + } + return rpn; + } + + /** + * Get a string representation of the RPN (Reverse Polish Notation) for this + * expression. + * + * @return A string with the RPN representation for this expression. + */ + public String toRPN() { + String result = new String(); + for (String st : getRPN()) { + result = result.isEmpty() ? result : result + " "; + result += st; + } + return result; + } + +} + diff --git a/ScientificCalculator/app/src/main/java/nyc/c4q/sufeiiz/scientificcalculator/MainActivity.java b/ScientificCalculator/app/src/main/java/nyc/c4q/sufeiiz/scientificcalculator/MainActivity.java new file mode 100644 index 0000000..a20bfe0 --- /dev/null +++ b/ScientificCalculator/app/src/main/java/nyc/c4q/sufeiiz/scientificcalculator/MainActivity.java @@ -0,0 +1,898 @@ +package nyc.c4q.sufeiiz.scientificcalculator; + +import android.support.v7.app.ActionBarActivity; +import android.os.Bundle; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.Button; +import android.widget.CompoundButton; +import android.widget.TextView; +import android.widget.Toast; +import android.widget.ToggleButton; + +import java.math.BigDecimal; + + +public class MainActivity extends ActionBarActivity { + + private TextView outputEq, outputAns; + private String equation, currNum, lastAns, lastNum, display; + private int count; + private boolean degMode = true; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + + outputEq = (TextView) findViewById(R.id.output_equation); + outputAns = (TextView) findViewById(R.id.output_answer); + if (savedInstanceState == null) { + outputEq.setText(""); + outputAns.setText(""); + display = ""; + equation = ""; + currNum = ""; + lastNum = ""; + lastAns = "0"; + count = 0; + } else { + outputAns.setText(savedInstanceState.getString("lastAns")); + outputEq.setText(savedInstanceState.getString("display")); + display = savedInstanceState.getString("display"); + equation = savedInstanceState.getString("equation"); + currNum = savedInstanceState.getString("currNum"); + lastNum = savedInstanceState.getString("lastNum"); + lastAns = savedInstanceState.getString("lastAns"); + count = savedInstanceState.getInt("count"); + } + + final Button clr = (Button) findViewById(R.id.btn_clear); + final Button ans = (Button) findViewById(R.id.btn_ans); + final Button negative = (Button) findViewById(R.id.btn_int); + final Button backspace = (Button) findViewById(R.id.btn_backspace); + final Button open = (Button) findViewById(R.id.btn_paren_open); + final Button close = (Button) findViewById(R.id.btn_paren_close); + final Button add = (Button) findViewById(R.id.btn_add); + final Button minus = (Button) findViewById(R.id.btn_sub); + final Button multiply = (Button) findViewById(R.id.btn_mult); + final Button divide = (Button) findViewById(R.id.btn_div); + final Button percent = (Button) findViewById(R.id.btn_percent); + final Button zero = (Button) findViewById(R.id.btn_0); + final Button one = (Button) findViewById(R.id.btn_1); + final Button two = (Button) findViewById(R.id.btn_2); + final Button three = (Button) findViewById(R.id.btn_3); + final Button four = (Button) findViewById(R.id.btn_4); + final Button five = (Button) findViewById(R.id.btn_5); + final Button six = (Button) findViewById(R.id.btn_6); + final Button seven = (Button) findViewById(R.id.btn_7); + final Button eight = (Button) findViewById(R.id.btn_8); + final Button nine = (Button) findViewById(R.id.btn_9); + final Button dot = (Button) findViewById(R.id.btn_decimal); + final Button equal = (Button) findViewById(R.id.btn_equals); + + // Scientific buttons + final Button factorial = (Button) findViewById(R.id.btn_factorial); + final Button pi = (Button) findViewById(R.id.btn_pi); + final Button e = (Button) findViewById(R.id.btn_e); + final Button sqRoot = (Button) findViewById(R.id.btn_sq_root); + final Button sq = (Button) findViewById(R.id.btn_sq); + final Button sin = (Button) findViewById(R.id.btn_sin); + final Button cos = (Button) findViewById(R.id.btn_cos); + final Button tan = (Button) findViewById(R.id.btn_tan); + final Button exp = (Button) findViewById(R.id.btn_exp); + final Button ln = (Button) findViewById(R.id.btn_ln); + final Button log = (Button) findViewById(R.id.btn_log); + + // Numbers OnClickListener + zero.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (display.isEmpty()) ; + else if (Numbers.lastInputIsConstant(display)) { + equation += "*"; + display += "×"; + } + currNum += "0"; + equation += "0"; + display += "0"; + outputEq.setText(display); + } + }); + one.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (display.isEmpty()) ; + else if (Numbers.lastInputIsConstant(display)) { + equation += "*"; + display += "×"; + } + currNum += "1"; + equation += "1"; + display += "1"; + outputEq.setText(display); + } + }); + two.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (display.isEmpty()) ; + else if (Numbers.lastInputIsConstant(display)) { + equation += "*"; + display += "×"; + } + currNum += "2"; + equation += "2"; + display += "2"; + outputEq.setText(display); + } + }); + three.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (display.isEmpty()) ; + else if (Numbers.lastInputIsConstant(display)) { + equation += "*"; + display += "×"; + } + currNum += "3"; + equation += "3"; + display += "3"; + outputEq.setText(display); + } + }); + four.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (display.isEmpty()) ; + else if (Numbers.lastInputIsConstant(display)) { + equation += "*"; + display += "×"; + } + currNum += "4"; + equation += "4"; + display += "4"; + outputEq.setText(display); + } + }); + five.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (display.isEmpty()) ; + else if (Numbers.lastInputIsConstant(display)) { + equation += "*"; + display += "×"; + } + currNum += "5"; + equation += "5"; + display += "5"; + outputEq.setText(display); + } + }); + six.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (display.isEmpty()) ; + else if (Numbers.lastInputIsConstant(display)) { + equation += "*"; + display += "×"; + } + currNum += "6"; + equation += "6"; + display += "6"; + outputEq.setText(display); + } + }); + seven.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (display.isEmpty()) ; + else if (Numbers.lastInputIsConstant(display)) { + equation += "*"; + display += "×"; + } + currNum += "7"; + equation += "7"; + display += "7"; + outputEq.setText(display); + } + }); + eight.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (display.isEmpty()) ; + else if (Numbers.lastInputIsConstant(display)) { + equation += "*"; + display += "×"; + } + currNum += "8"; + equation += "8"; + display += "8"; + outputEq.setText(display); + } + }); + nine.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (display.isEmpty()) ; + else if (Numbers.lastInputIsConstant(display)) { + equation += "*"; + display += "×"; + } + currNum += "9"; + equation += "9"; + display += "9"; + outputEq.setText(display); + } + }); + + // if number already contains ".", ignore + // if user omits 0 before ".", include 0 + dot.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (currNum.contains(".")) ; + else if (currNum.equals("")) { + currNum += "0."; + equation += "0."; + display += "0."; + } else { + equation += "."; + currNum += "."; + display += "."; + } + outputEq.setText(display); + } + }); + + // clear everything + clr.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + equation = ""; + currNum = ""; + lastAns = ""; + lastNum = ""; + display = ""; + outputAns.setText(""); + outputEq.setText(display); + } + }); + + // TODO fix backspace for sincostan once that's implemented + // if equation is empty, do nothing + // else if the last input was %, convert to decimal to find length of converted num + // else delete last char in currNum, equation, and display + backspace.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (equation.isEmpty()) ; + else if (display.charAt(display.length() - 1) == '%') { + display = display.substring(0, display.length() - 1); // removes "%" + + // find length of converted decimal and remove from equation; add back current num + String converted = Numbers.percentage(currNum, lastNum); + equation = equation.substring(0, equation.length() - converted.length()); + equation += currNum; + } else if (display.charAt(display.length() - 1) == '!') { + display = display.substring(0, display.length() - 1); // removes "!" + + String converted = String.valueOf(Numbers.factorial(Integer.valueOf(currNum))); + equation = equation.substring(0, equation.length() - converted.length()); + equation += currNum; + } else if (display.charAt(display.length() - 1) == 'e' || + display.charAt(display.length() - 1) == 'π') { + equation = equation.substring(0, equation.length() - 13); + currNum = ""; + display = display.substring(0, display.length() - 1); + } else if (display.charAt(display.length() - 1) == 's') { + equation = equation.substring(0, equation.length() - currNum.length()); + currNum = ""; + display = display.substring(0, display.length() - 3); + } else { + if (currNum.length() > 0) + currNum = currNum.substring(0, currNum.length() - 1); + if (equation.length() > 0) + equation = equation.substring(0, equation.length() - 1); + if (display.length() > 0) + display = display.substring(0, display.length() - 1); + } + outputEq.setText(display); + } + }); + + // if equation is empty and current is not empty, add current to equation + // else if only equation is empty, ignore (needed so there's no out of range error) + // else if last input was operator or (, replace + // else just add operator + add.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (equation.isEmpty() && !lastAns.isEmpty()) { + lastNum = lastAns; + equation = lastAns + "+"; + display = lastAns + "+"; + } else if (equation.isEmpty()) ; + else if (Numbers.lastInputIsOperator(equation)) { + equation = equation.substring(0, equation.length() - 1) + "+"; + display = display.substring(0, display.length() - 1) + "+"; + } else { + equation += "+"; + lastNum = currNum; + currNum = ""; + display += "+"; + } + outputEq.setText(display); + } + }); + minus.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (equation.isEmpty() && !lastAns.isEmpty()) { + lastNum = lastAns; + equation = lastAns + "-"; + display = lastAns + "-"; + } else if (equation.isEmpty()) ; + else if (Numbers.lastInputIsOperator(equation)) { + equation = equation.substring(0, equation.length() - 1) + "-"; + display = display.substring(0, display.length() - 1) + "-"; + } else { + equation += "-"; + lastNum = currNum; + currNum = ""; + display += "-"; + } + outputEq.setText(display); + } + }); + multiply.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (equation.isEmpty() && !lastAns.isEmpty()) { + lastNum = lastAns; + equation = lastAns + "*"; + display = lastAns + "×"; + } else if (equation.isEmpty()) ; + else if (Numbers.lastInputIsOperator(equation)) { + equation = equation.substring(0, equation.length() - 1) + "*"; + display = display.substring(0, display.length() - 1) + "×"; + } else { + equation += "*"; + lastNum = currNum; + currNum = ""; + display += "×"; + } + outputEq.setText(display); + } + }); + divide.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (equation.isEmpty() && !lastAns.isEmpty()) { + lastNum = lastAns; + equation = lastAns + "/"; + display = lastAns + "÷"; + } else if (equation.isEmpty()) ; + else if (Numbers.lastInputIsOperator(equation)) { + equation = equation.substring(0, equation.length() - 1) + "/"; + display = display.substring(0, display.length() - 1) + "÷"; + } else { + equation += "/"; + lastNum = currNum; + currNum = ""; + display += "÷"; + } + outputEq.setText(display); + } + }); + + // if equation is empty, ignore + // else if last input was operator or ( or %, ignore + // else convert percentage to number + percent.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (equation.isEmpty()) ; + else if (Numbers.lastInputIsOperator(equation) || + Numbers.lastInputIsPercent(equation)) ; + else { + equation = equation.substring(0, equation.length() - currNum.length()); + String converted = Numbers.percentage(currNum, lastNum); + + equation += converted; + display += "%"; + outputEq.setText(display); + } + } + }); + + // if equation is empty, add - accordingly + // else if last input was %, find length of converted number and add - accordingly + // else if last input was e or pi, find length of converted number and add - accordingly + // else if last input was ans, find length of converted number and add - accordingly + // else add - accordingly + negative.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (equation.isEmpty()) { + if (currNum.contains("-")) + currNum = currNum.substring(1); + else + currNum = "-" + currNum; + equation += currNum; + display += currNum; + } else if (Numbers.lastInputIsPercent(display)) { + String converted = Numbers.percentage(currNum, lastNum); + display = display.substring(0, display.length() - currNum.length() - 1); + equation = equation.substring(0, equation.length() - converted.length()); + if (currNum.contains("-")) { + currNum = currNum.substring(1); + display += currNum + "%"; + equation += converted.substring(1); + } else { + currNum = "-" + currNum; + display += currNum + "%"; + equation += "-" + converted; + } + } else if (display.charAt(display.length() - 1) == 'e' || + display.charAt(display.length() - 1) == 'π') { + char constant = display.charAt(display.length() - 1); + if (currNum.contains("-")) { + currNum = currNum.substring(1); + equation = equation.substring(0, equation.length() - 14) + currNum; + display = display.substring(0, display.length() - 2) + constant; + } else { + currNum = "-" + currNum; + equation = equation.substring(0, equation.length() - 13) + "-" + currNum; + display = display.substring(0, display.length() - 1) + "-" + constant; + } + } else if (display.charAt(display.length() - 1) == 's') { + if (currNum.equals("0")) { + display = display.substring(0, display.length() - 3) + "-" + "Ans"; + } else if (currNum.contains("-")) { + currNum = currNum.substring(1); + equation = equation.substring(0, equation.length() - currNum.length() - 1) + currNum; + display = display.substring(0, display.length() - 4) + "Ans"; + } else { + currNum = "-" + currNum; + equation = equation.substring(0, equation.length() - currNum.length() + 1) + currNum; + display = display.substring(0, display.length() - 3) + "-" + "Ans"; + } + } else if (display.charAt(display.length() - 1) == '^') { + if (currNum.contains("-")) { + currNum = currNum.substring(1); + display = display.substring(0, display.length() - currNum.length() - 1) + currNum; + equation = equation.substring(0, equation.length() - currNum.length() - 1) + currNum; + } else { + currNum = "-" + currNum; + display = display.substring(0, display.length() - currNum.length() + 1) + currNum; + equation = equation.substring(0, equation.length() - currNum.length() + 1) + currNum; + } + } else { + if (currNum.contains("-")) { + equation = equation.substring(0, equation.length() - currNum.length()); + display = display.substring(0, display.length() - currNum.length()); + currNum = currNum.substring(1); + } else { + equation = equation.substring(0, equation.length() - currNum.length()); + display = display.substring(0, display.length() - currNum.length()); + currNum = "-" + currNum; + } + equation += currNum; + display += currNum; + } + outputEq.setText(display); + } + }); + + // increase count for every opened parentheses + // if equation if empty, open parentheses + // else if last input was a number or last input was ), add multiply before open + // else just open + open.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (equation.isEmpty()) { + equation += "("; + display += "("; + } else if (Character.isDigit(equation.charAt(equation.length() - 1)) || + equation.charAt(equation.length() - 1) == ')' || + Numbers.lastInputIsConstant(display)) { + equation += "*("; + display += "×("; + } else { + display += "("; + equation += "("; + } + count++; + outputEq.setText(display); + } + }); + + // decrease count for every closed parentheses + // if equation if empty or count is less than zero or last input was operator, ignore + // else just close + close.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (equation.isEmpty() || count <= 0 || + Numbers.lastInputIsOperator(equation)) ; + else { + equation += ")"; + display += ")"; + count--; + outputEq.setText(display); + } + } + }); + + // save last answer (whenever = is clicked) + ans.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + lastNum = currNum; + currNum = lastAns; + if (lastAns.isEmpty()) ; + else if (display.isEmpty()) { + equation += lastAns; + display += "Ans"; + } else if (Numbers.lastInputIsConstant(display) || + Character.isDigit(display.charAt(display.length() - 1))) { + equation += "*" + lastAns; + display += "×Ans"; + } else { + equation += lastAns; + display += "Ans"; + } + outputEq.setText(display); + } + }); + + // if parentheses were not closed properly, close them + // else if last input was operator, display error message + // else parse equation for answer + equal.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (count > 0) { + for (; count > 0; count--) { + equation += ")"; + } + } + if (equation.equals("")) + outputEq.setText(""); + else { + try { + BigDecimal answer = new Expression(equation).eval(); + + lastAns = String.valueOf(answer.doubleValue()); + + // returns long if answer is a whole number, otherwise return double + if (lastAns.substring(lastAns.length() - 2).equals(".0")) + lastAns = String.valueOf(answer.longValue()); + } catch (Exception e) { + equation = ""; + currNum = ""; + lastNum = ""; + display = ""; + outputEq.setText("Error"); + } + + lastNum = ""; + currNum = ""; + equation = ""; + display = ""; + outputAns.setText(lastAns); + } + } + }); + + // Scientific calculator + if (log != null) { + + // Toggle radians/degrees + ToggleButton toggle = (ToggleButton) findViewById(R.id.btn_rad); + toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + if (isChecked) { + Toast.makeText(MainActivity.this, "Radians mode on", Toast.LENGTH_SHORT).show(); + degMode = false; + } else { + Toast.makeText(MainActivity.this, "Degrees mode on", Toast.LENGTH_SHORT).show(); + degMode = true; + } + } + }); + + // if equation if empty, ignore + // else last operator was an operator, ignore + // else try factorial calculation, catch error + factorial.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (equation.isEmpty()) ; + else if (Numbers.lastInputIsOperator(equation)) ; + else { + try { + equation = equation.substring(0, equation.length() - currNum.length()); + currNum = String.valueOf(Numbers.factorial(Integer.valueOf(currNum))); + equation += currNum; + display += "!"; + outputEq.setText(display); + } catch (Exception e) { + equation = ""; + currNum = ""; + lastNum = ""; + display = ""; + outputEq.setText("Error"); + } + } + } + }); + pi.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + currNum = String.valueOf(3.14159265359); + if (display.isEmpty()) { + equation += currNum; + display += "π"; + } else if (Numbers.lastInputIsConstant(display) || + Character.isDigit(display.charAt(display.length() - 1)) || + display.charAt(display.length() - 1) == ')') { + equation += "*" + currNum; + display += "×π"; + } else { + equation += currNum; + display += "π"; + } + outputEq.setText(display); + } + }); + e.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + currNum = String.valueOf(2.71828182846); + if (display.isEmpty()) { + equation += currNum; + display += "e"; + } else if (Numbers.lastInputIsConstant(display) || + Character.isDigit(display.charAt(display.length() - 1)) || + display.charAt(display.length() - 1) == ')') { + equation += "*" + currNum; + display += "×e"; + } else { + equation += currNum; + display += "e"; + } + outputEq.setText(display); + } + }); + + sin.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (degMode) { + if (equation.isEmpty()) { + equation += "SIN("; + display += "sin("; + } else if (Character.isDigit(equation.charAt(equation.length() - 1)) || + equation.charAt(equation.length() - 1) == ')' || + Numbers.lastInputIsConstant(display)) { + equation += "*SIN("; + display += "×sin("; + } else { + equation += "SIN("; + display += "sin("; + } + } else { + if (equation.isEmpty()) { + equation += "RAD(SIN("; + display += "sin("; + } else if (Character.isDigit(equation.charAt(equation.length() - 1)) || + equation.charAt(equation.length() - 1) == ')' || + Numbers.lastInputIsConstant(display)) { + equation += "*RAD(SIN("; + display += "×sin("; + } else { + equation += "RAD(SIN("; + display += "sin("; + } + count++; + } + count++; + outputEq.setText(display); + } + }); + cos.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (degMode) { + if (equation.isEmpty()) { + equation += "COS("; + display += "cos("; + } else if (Character.isDigit(equation.charAt(equation.length() - 1)) || + equation.charAt(equation.length() - 1) == ')' || + Numbers.lastInputIsConstant(display)) { + equation += "*COS("; + display += "×cos("; + } else { + equation += "COS("; + display += "cos("; + } + } else { + if (equation.isEmpty()) { + equation += "RAD(COS("; + display += "cos("; + } else if (Character.isDigit(equation.charAt(equation.length() - 1)) || + equation.charAt(equation.length() - 1) == ')' || + Numbers.lastInputIsConstant(display)) { + equation += "*RAD(COS("; + display += "×cos("; + } else { + equation += "RAD(COS("; + display += "cos("; + } + count++; + } + count++; + outputEq.setText(display); + } + }); + tan.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (degMode) { + if (equation.isEmpty()) { + equation += "TAN("; + display += "tan("; + } else if (Character.isDigit(equation.charAt(equation.length() - 1)) || + equation.charAt(equation.length() - 1) == ')' || + Numbers.lastInputIsConstant(display)) { + equation += "*TAN("; + display += "×tan("; + } else { + equation += "TAN("; + display += "tan("; + } + } else { + if (equation.isEmpty()) { + equation += "RAD(TAN("; + display += "tan("; + } else if (Character.isDigit(equation.charAt(equation.length() - 1)) || + equation.charAt(equation.length() - 1) == ')' || + Numbers.lastInputIsConstant(display)) { + equation += "*RAD(TAN("; + display += "×tan("; + } else { + equation += "RAD(TAN("; + display += "tan("; + } + count++; + } + count++; + outputEq.setText(display); + } + }); + ln.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (equation.isEmpty()) { + equation += "LOG("; + display += "ln("; + } else if (Character.isDigit(equation.charAt(equation.length() - 1)) || + equation.charAt(equation.length() - 1) == ')' || + Numbers.lastInputIsConstant(display)) { + equation += "*LOG("; + display += "×ln("; + } else { + equation += "LOG("; + display += "ln("; + } + count++; + outputEq.setText(display); + } + }); + log.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (equation.isEmpty()) { + equation += "LOG10("; + display += "log("; + } else if (Character.isDigit(equation.charAt(equation.length() - 1)) || + equation.charAt(equation.length() - 1) == ')' || + Numbers.lastInputIsConstant(display)) { + equation += "*LOG10("; + display += "×log("; + } else { + equation += "LOG10("; + display += "log("; + } + count++; + outputEq.setText(display); + } + }); + sqRoot.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (equation.isEmpty()) { + equation += "SQRT("; + display += "√("; + } else if (Character.isDigit(equation.charAt(equation.length() - 1)) || + equation.charAt(equation.length() - 1) == ')' || + Numbers.lastInputIsConstant(display)) { + equation += "*SQRT("; + display += "×√("; + } else { + equation += "SQRT("; + display += "√("; + } + count++; + outputEq.setText(display); + } + }); + + exp.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (display.isEmpty()) ; + else if (Character.isDigit(display.charAt(display.length() - 1))) { + equation = equation.substring(0, display.length() - currNum.length()) + "(" + currNum; + lastNum = currNum; + currNum = "E"; + equation += "*(10^"; + display += "E"; + } + } + }); + + sq.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (equation.isEmpty() || + equation.charAt(equation.length() - 1) == '(') ; + else { + lastNum = currNum; + currNum = ""; + equation += "^"; + display += "^"; + } + outputEq.setText(display); + } + }); + } + } + + @Override + protected void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + outState.putString("currNum", currNum); + outState.putString("equation", equation); + outState.putString("lastAns", lastAns); + outState.putString("display", display); + outState.putString("lastNum", lastNum); + outState.putInt("count", count); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + getMenuInflater().inflate(R.menu.menu_main, menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + + //noinspection SimplifiableIfStatement + if (id == R.id.action_settings) { + return true; + } + + return super.onOptionsItemSelected(item); + } +} \ No newline at end of file diff --git a/ScientificCalculator/app/src/main/java/nyc/c4q/sufeiiz/scientificcalculator/Numbers.java b/ScientificCalculator/app/src/main/java/nyc/c4q/sufeiiz/scientificcalculator/Numbers.java new file mode 100644 index 0000000..28d22e5 --- /dev/null +++ b/ScientificCalculator/app/src/main/java/nyc/c4q/sufeiiz/scientificcalculator/Numbers.java @@ -0,0 +1,64 @@ +package nyc.c4q.sufeiiz.scientificcalculator; + +import android.view.View; +import android.widget.TextView; + +import java.util.Arrays; + +/** + * Created by sufeizhao on 5/5/15. + */ +public class Numbers extends MainActivity{ + + // returns String of the percentage as a decimal + public static String percentage(String num, String lastNum) { + String converted; + double newCurr = (Double.valueOf(num) / 100); + + if (lastNum.isEmpty()) { + converted = String.valueOf(newCurr); + } else { + newCurr = Double.valueOf(lastNum) * newCurr; + converted = String.valueOf(newCurr); + } + + return converted; + } + + // returns true if last input was +, -, *, /, ( + public static boolean lastInputIsOperator(String equation) { + String[] operators = {"+", "-", "*", "/", "("}; + return Arrays.asList(operators).contains(String.valueOf(equation.charAt(equation.length() - 1))); + } + + // returns true if last input was % + public static boolean lastInputIsPercent(String display) { + return display.charAt(display.length() - 1) == '%'; + } + + public static boolean lastInputIsConstant(String display) { + return display.charAt(display.length() - 1) == 's' || + display.charAt(display.length() - 1) == 'π' || + display.charAt(display.length() - 1) == 'e'; + } + + // returns factorial answer + static boolean negative = false; + public static double factorial(int x) { + if (x < 0) { + x *= -1; + negative = true; + } + if (x == 1) { + if (negative) { + return -1; + } else { + return 1; + } + } else if (x == 0) { + return 1; + } else { + return x * factorial(x-1); + } + } +} \ No newline at end of file diff --git a/ScientificCalculator/app/src/main/res/drawable/box.xml b/ScientificCalculator/app/src/main/res/drawable/box.xml new file mode 100644 index 0000000..ddee7f3 --- /dev/null +++ b/ScientificCalculator/app/src/main/res/drawable/box.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/ScientificCalculator/app/src/main/res/drawable/button_bg_color.xml b/ScientificCalculator/app/src/main/res/drawable/button_bg_color.xml new file mode 100644 index 0000000..1f08fb4 --- /dev/null +++ b/ScientificCalculator/app/src/main/res/drawable/button_bg_color.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/ScientificCalculator/app/src/main/res/drawable/button_text_color.xml b/ScientificCalculator/app/src/main/res/drawable/button_text_color.xml new file mode 100644 index 0000000..99b18ac --- /dev/null +++ b/ScientificCalculator/app/src/main/res/drawable/button_text_color.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/ScientificCalculator/app/src/main/res/layout-land/activity_main.xml b/ScientificCalculator/app/src/main/res/layout-land/activity_main.xml new file mode 100644 index 0000000..e7eed11 --- /dev/null +++ b/ScientificCalculator/app/src/main/res/layout-land/activity_main.xml @@ -0,0 +1,462 @@ + + + + + + + + + + + + + + + + + + + + + + + + + +