Making a calculator but no way to retrieve functions - android

An easy way to make an android calculator would be to have 3 separate edit text boxes and have the user in put a number, a function, and then another number like 3 + 3. This would make it easier for the app dev to store the number(s) and function(s) and perform a calculation.
Now... my calculator app has the ability to out put all the input real-time, the down side is that when I retrieve what's in the input box, i retrieve it as string (to make sure i include all the functions input-ed). I know how to retrieve numbers (by using int parse) but how do I retrieve the functions such as + - / * ? (They're the main bit!! :O). Any help would me much appreciated thanks :)

Try to use a switch that analyze and identify the correct operation. Something like this:
(I suppose the content of function EditText in a string named functionSign
...
switch(functionSign)
{
case "+": return op1+op2;
case "-": return op1-op2;
...
EDIT 2:
I suppose that user can put only the functions simbols + - / * and the operations are organized in a method:
public double calculate()
{
String operations= inputEditText.getText().toString();
StringTokenizer st= new StringTokenizer(operations);
//to calculate in input must have at last one operation and two operands
//the first token must be a number (the operation scheme is (number)(function)(numeber)...)
double result=Double.parseDouble(st.nextToken());
while(st.hasMoreTokens())
{
String s=st.nextToken();
if(s.equals("+"))
result += Double.parseDouble(st.nextToken());
else if(s.equals("-"))
result -= Double.parseDouble(st.nextToken());
else if(s.equals("*"))
result *= Double.parseDouble(st.nextToken());
else if(s.equals("/"))
result /= Double.parseDouble(st.nextToken());
else
throw new Exception();
}
return result;
}
This code is a really simple example, you must be sure that the user don't try to calculate something incomplete like:
3 + 3 -
/ 3 * 5
and similar. What the user should be able to do is your decision

You can get the operator as a string and use if statements to determine what to do:
String operator=operatorEditText.getText().toString();
if (operator.equals("+")){
//addition code here
}
else if (operator.equals("-")){
//subtraction code here
}
...

Related

Android: Converting a set of functions into an equation

I am 99% sure that this cannot be done, however I thought I would ask to be certain.
I am attempting to create an application that calculates the required dice roll for an action in a popular tabletop war game.
The following is this calculation in Java
int x = ((WSattacker * 2) - WSdefender);
int y = (WSattacker - WSdefender);
String result;
// Calculation for a +5
if (x <= -1) {
result = "5+";
}
// Calculation for a +4
else if (x >= 0 && y <= 0) {
result = "4+";
}
// Calculation for a +3
else if (y > 0) {
result = "3+";
} else {
result = "Error";
}
return result;
Now my issue is that to avoid copywriter infringement I cannot mention the name of the game in my application, and probably cannot hard code the above calculation in the app.
This means that it is difficult to tell a potential user what the app will do.
The only solution I can think of is to make the application generic and allow the user to input the calculation required in the form of an equation.
An equation that I can place anonymously on a public board or similar.
Therefore my questions are as follows.
Is there another way of going about this?
If no, is it possible to condense the above code into a single expression/ equationi.e. one that removes the if and else statements
To answer question 2:
result = test_condition_1 ? result2_if_true : (test_condition_2 ? result2_if_true : test3_or_result2);
You can then build up 'compound' test conditions this way, and it's based upon ternary operators.
EDIT
Ternary operators are a short-hand way of writing if..then..else statments, and more information can be found in the wiki-link above. An example of its use is below, which you can compile and run:
public class TernaryTest {
public static void main(String [] args){
int x = 14;
int y = 5;
String result = ( x <= 10 ) ? "Less than 10" : "More than 10";
System.out.println("Result is: " + result);
}
}
Try running it and see the result as you change the value of x to understand how it works. Then it's possible to extend it to include and else by replacing the "more than 10" string.

Why 1 divided by 1.1 doesn't work, even when I'm using BigDecimal in my code?

I'm trying to do a calculator with the 4 basic operations. I started using doubles to get the arguments from edittext, but I discovered the problem with decimal values. To avoid that, I used BigDecimal, but now the app is failing at some specific numbers, as 1/(1.1). I noticed only the divide function is wrecking the app, add,sub and multiply are working fine. I really would appreciate some help with this. Here's part of the code:
div.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
if(! num1 .getEditableText().toString().matches("") && !num2 .getEditableText().toString().matches(""))
{String valor1 =num1.getText().toString();
String valor2 =num2.getText().toString();
BigDecimal a = new BigDecimal(valor1);
BigDecimal b = new BigDecimal(valor2);
BigDecimal result = a.divide(b);
Toast.makeText(MainActivity.this,"="+result, Toast.LENGTH_LONG).show();
} }
});
If the quotient has a nonterminating decimal expansion and the operation is specified to return an exact result, an ArithmeticException is thrown. Otherwise, the exact result of the division is returned, as done for other operations.
Use divide method like that
a.divide(b, 2, RoundingMode.HALF_UP)
where 2 is precision and RoundingMode.HALF_UP is rounding mode
source:https://stackoverflow.com/a/4591216/1589566
It crashes on an ArithmeticException because the result is a number with infinite decimals.
From http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html
"In the case of divide, the exact quotient could have an infinitely long decimal expansion; for example, 1 divided by 3. If the quotient has a nonterminating decimal expansion and the operation is specified to return an exact result, an ArithmeticException is thrown. Otherwise, the exact result of the division is returned, as done for other operations"
In your country it may be ',' and not '.'
String valor1 = num1.getText().toString().replace('.', ',');
Try this and tell us if it works !

Determine if content in editText is a "." ONLY

I have written a calculator type app. My mates found that entering single decimal points only into the editText's makes the app crash. Decimal numbers and integers work fine, but I get a number format exception when .'s are entered.
I want to check if a single . has been placed in an editText, in order for me to display a toast telling the user to stop trying to crash the app.
My issue is that a . doesn't have a numerical value...
You can wrap it in a try/catch which should be done anyway when parsing text. So something like
try
{
int someInt = Integer.parseInt(et.getText().toString());
// other code
}
catch (NumberFormatException e)
{
// notify user with Toast, alert, etc...
}
This way it will protect against any number format exception and will make the code more reusable later on.
You can treat .1 as 0.1 by the following.
String text = et.getText().toString();
int len = text.length();
// Do noting if edit text just contains a "." without numbers
if(len==0 || (len==1 && text.charAt(0).equals(".")))
return;
if(text.charAt(0).equals(".") && text.length() > 1) {
text = "0" + text;
}
// Do your parsing and calculations

Trying to only do math functions on edittexts users have entered information in on android

I have a 10-field average lap calculator. However, in testing, someone said they normally only run X laps in practice, vs. 10 (let's say 7).
I think I could use an if statement, but there'd be at least 10 of them and a bunch of clumsy code, and I'm not sure on arrays/switch statements exactly. I think all of those might be possible, but my low level of experience has yet to fully comprehend these useful tools.
CURRENT CODE:
double tenLapAvgVar = ((lap1Var + lap2Var + lap3Var + lap4Var + lap5Var + lap6Var + lap7Var + lap8Var + lap9Var + lap10Var) / 10);
So essentially, if someone leaves a field or fields blank, I want to calculate the average based on the populated fields, not 10 (if they leave 3 fields blank, calculate based on 7, for instance). Any help you guys could provide would be much appreciated, thanks!
You could have an ArrayList<EditText> object and a method which iterates over it and adds up the values. Something like:
public double getLapAverage()
{
int noOfCompletedLaps = 0;
double lapAve = 0;
double lapsTotal = 0;
for(EditText text : textBoxes)
{
if(text.getText().toString().length() > 0)
{
//psuedo code, and assuming text is numerical
lapsTotal += Double.parse(text.getText().toString());
noOfCompletedLaps++;
}
}
if( noOfCompletedLaps > 0)
{
lapAve = lapsTotal / noOfCompletedLaps;
}
return lapAve;
}
Maybe it would be better if you used an array instead of 10 different variables.
Then you can use a for statement and initialize them to 0, afterwords let the user fill the array and count how many are not zero.
Finally sum up all the array and divide by the count you previously calculated.

Detecting only the last two digits in text entry box for a calculator app

I'm still pretty new to this, but I'm trying to make a calculator for myself to use at work; similar to a resistor calculator.
I am hope to change a textview and imageview according to the last two digits entered into a edittext box. For example, if I were to type in "9,000,011", I would want to display a certain color of image and text that corresponds with "11" and the same color and text for say 1,000,011. Also different for 12, 13, and so on. this way No matter what number I type it only looks at the last two digits. Does anyone know the way to do this or maybe can just point me in the right direction?
here is how I'm
private void calculate() {
number = Double.parseDouble(inputnumber.getText().toString());
ImageView iv = (ImageView) this.findViewById(R.id.pairimage);
if (number == 6000001) {
iv.setImageResource(R.drawable.white);
txtnumber.setText("White");
} else if (number == 6000002) {
iv.setImageResource(R.drawable.red);
txtnumber.setText("Red");
}
//*and so on, all the way up to 99*
}
If you want just the last two, then I would use
String wholeNumber = inputnumber.getText().toString();
int n = Integer.valueOf(wholeNumber.subString(wholeNumber.length()-2, wholeNumber.length()-1);
and then a switch block:
switch(n) {
case 1:
iv.setImageResource(R.drawable.white);
txtnumber.setText("White");
break;
case 2:
iv.setImageResource(R.drawable.red);
txtnumber.setText("Red");
break;
}
etc.
Maybe convert the number to a String and then look at that e.g.
String theNumber = String.valueOf(number);
String lastTwoDigits =
theNumber.substring(theNumber.length() -2, theNumber.length());
Then you can have your if statements to read the lastTwoDigits. Or convert back to int (Integer.valueOf(lastTwoDigits); and use a switch statement. Or put the values 0-99 into a Map and have a Command object or something as the value which gets executed.
Obviously you'll need some validation here on the user input.
You have a couple of options. The easiest one is to use the modulus operator like:
number = number % 100;
switch (number) {
case 1:
// do stuff;
break;
case 2:
// do stuff;
break;
}
For this to work, though, "number" will have to be an integer. It's an integer in your examples, so that may work for you; otherwise you can try some math tricks like:
int number2 = (int)(number * 100) % 100;
Go with the sub-string approach. I've found that some number combinations don't multiply/divide well in java.

Categories

Resources