I am designing a calculator in android. If I do for example 5+5 and then hit =, I get 10. However, if I do 5+5+5 and then hit =, I still get 10. I want my calculator to handle multiple operands so that when I do 5+5+5 for example, I get 15 when I hit equals.
Here's what I have so far:
package edu.uwstout.pocketcalculator;
import java.text.DecimalFormat;
import java.util.ArrayList;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Basic extends Activity {
private Button one, two, three, four,
five, six, seven, eight, nine, zero,
add, subtract, multiply, divide, decimal,
negative, enter, clear;
private TextView output;
double numberOne;
double numberTwo;
double total;
double plusMinus;
int plus;
int minus;
int multiply_counter;
int divide_counter;
int decimal_counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic);
one = (Button) findViewById(R.id.b1);
one.setTextColor(Color.BLACK);
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
output.setText(output.getText() + "1");
}
});
two = (Button) findViewById(R.id.b2);
two.setTextColor(Color.BLACK);
two.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
output.setText(output.getText() + "2");
}
});
three = (Button) findViewById(R.id.b3);
three.setTextColor(Color.BLACK);
three.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
output.setText(output.getText() + "3");
}
});
four = (Button) findViewById(R.id.b4);
four.setTextColor(Color.BLACK);
four.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
output.setText(output.getText() + "4");
}
});
five = (Button) findViewById(R.id.b5);
five.setTextColor(Color.BLACK);
five.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
output.setText(output.getText() + "5");
}
});
six = (Button) findViewById(R.id.b6);
six.setTextColor(Color.BLACK);
six.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
output.setText(output.getText() + "6");
}
});
seven = (Button) findViewById(R.id.b7);
seven.setTextColor(Color.BLACK);
seven.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
output.setText(output.getText() + "7");
}
});
eight = (Button) findViewById(R.id.b8);
eight.setTextColor(Color.BLACK);
eight.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
output.setText(output.getText() + "8");
}
});
nine = (Button) findViewById(R.id.b9);
nine.setTextColor(Color.BLACK);
nine.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
output.setText(output.getText() + "9");
}
});
zero = (Button) findViewById(R.id.b0);
zero.setTextColor(Color.BLACK);
zero.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
output.setText(output.getText() + "9");
}
});
decimal = (Button) findViewById(R.id.bDot);
decimal.setTextColor(Color.BLACK);
decimal.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(decimal_counter == 0){
output.setText(output.getText() + ".");
}
decimal_counter = 1;
}
});
negative = (Button) findViewById(R.id.bNeg);
negative.setTextColor(Color.BLACK);
negative.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
plusMinus=(Double.parseDouble(String.valueOf(output.getText())));
plusMinus=plusMinus*(-1);
output.setText(String.valueOf(plusMinus));
}
});
add = (Button) findViewById(R.id.bPlus);
add.setTextColor(Color.BLACK);
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
numberOne=(Double.parseDouble(String.valueOf(output.getText())));
plus = 1;
output.setText("");
decimal_counter=0;
}
});
subtract = (Button) findViewById(R.id.bMinus);
subtract.setTextColor(Color.BLACK);
subtract.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
numberOne=(Double.parseDouble(String.valueOf(output.getText())));
output.setText("");
minus=1;
decimal_counter=0;
}
});
multiply = (Button) findViewById(R.id.bTimes);
multiply.setTextColor(Color.BLACK);
multiply.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
numberOne=(Double.parseDouble(String.valueOf(output.getText())));
output.setText("");
multiply_counter=1;
decimal_counter=0;
}
});
divide = (Button) findViewById(R.id.bDivide);
divide.setTextColor(Color.BLACK);
divide.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
numberOne=(Double.parseDouble(String.valueOf(output.getText())));
output.setText("");
divide_counter=1;
decimal_counter=0;
}
});
enter = (Button) findViewById(R.id.bEnter);
enter.setTextColor(Color.BLACK);
enter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
output.setText(String.valueOf(enter(numberOne)));
}
});
clear = (Button) findViewById(R.id.bClear);
clear.setTextColor(Color.BLACK);
clear.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
output.setText("");
decimal_counter=0;
}
});
output = (TextView) findViewById(R.id.bOutput);
registerForContextMenu(output);
}
public double enter(double numberOne){
numberTwo = (Double.parseDouble(String.valueOf(output.getText())));
if(plus>0){
total = numberOne + numberTwo;
numberOne = 0;
numberTwo = 0;
plus = 0;
return total;
}
if(minus>0){
total = numberOne - numberTwo;
numberOne = 0;
numberTwo = 0;
minus = 0;
return total;
}
if(multiply_counter>0){
total = numberOne * numberTwo;
numberOne = 0;
numberTwo = 0;
multiply_counter = 0;
return total;
}
if(divide_counter>0){
total = numberOne / numberTwo;
numberOne = 0;
numberTwo = 0;
divide_counter = 0;
return total;
}
return total;
}
}
it seems that you are replacing your numberOne every time when an operand is clicked...
so try to perform calculation after every operand click ... check if numberOne contains value and if it contains perform the operation and store the value to numberOne...
otherwise just put the value to numberOne without performing calculation..
Related
This question already has answers here:
How to nicely format floating numbers to string without unnecessary decimal 0's
(29 answers)
Closed 2 years ago.
I am making an android calculator in android studio. But, in my calculator when the result is a full number, the number appears with decimal 0.
For example, if i add 9 and 11 the result is appearing as 20.0
So, how do i remove .0 from the result for a full number(ex:- 10,24).
This is my MainActivity.java
package com.example.calculator;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.faendir.rhino_android.RhinoAndroidHelper;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ast.Scope;
public class MainActivity extends AppCompatActivity {
Button btn0,btn1,btn2,btn3,btn4,btn5,btn6,btn7,btn8,btn9,btnPercent,btnPlus,btnMinus,btnMultiply,btnDivision,btnEqual,btnClear,btnDot,btnBracket,btnBackspace;
TextView tvInput,tvOutput;
String process;
boolean checkBracket = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn0 = findViewById(R.id.btn0);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
btn3 = findViewById(R.id.btn3);
btn4 = findViewById(R.id.btn4);
btn5 = findViewById(R.id.btn5);
btn6 = findViewById(R.id.btn6);
btn7 = findViewById(R.id.btn7);
btn8 = findViewById(R.id.btn8);
btn9 = findViewById(R.id.btn9);
btnPlus = findViewById(R.id.btnPlus);
btnMinus = findViewById(R.id.btnMinus);
btnDivision = findViewById(R.id.btnDivision);
btnMultiply = findViewById(R.id.btnMultiply);
btnEqual = findViewById(R.id.btnEqual);
btnClear = findViewById(R.id.btnClear);
btnDot = findViewById(R.id.btnDot);
btnPercent = findViewById(R.id.btnPercent);
btnBracket = findViewById(R.id.btnBracket);
btnBackspace = findViewById(R.id.btnBackspace);
tvInput = findViewById(R.id.tvInput);
tvOutput = findViewById(R.id.tvOutput);
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvInput.setText("");
tvOutput.setText("");
}
});
btn0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
process = tvInput.getText().toString();
tvInput.setText(process + "0");
}
});
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
process = tvInput.getText().toString();
tvInput.setText(process + "1");
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
process = tvInput.getText().toString();
tvInput.setText(process + "2");
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
process = tvInput.getText().toString();
tvInput.setText(process + "3");
}
});
btn4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
process = tvInput.getText().toString();
tvInput.setText(process + "4");
}
});
btn5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
process = tvInput.getText().toString();
tvInput.setText(process + "5");
}
});
btn6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
process = tvInput.getText().toString();
tvInput.setText(process + "6");
}
});
btn6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
process = tvInput.getText().toString();
tvInput.setText(process + "6");
}
});
btn7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
process = tvInput.getText().toString();
tvInput.setText(process + "7");
}
});
btn8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
process = tvInput.getText().toString();
tvInput.setText(process + "8");
}
});
btn9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
process = tvInput.getText().toString();
tvInput.setText(process + "9");
}
});
btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
process = tvInput.getText().toString();
tvInput.setText(process + "+");
}
});
btnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
process = tvInput.getText().toString();
tvInput.setText(process + "-");
}
});
btnMultiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
process = tvInput.getText().toString();
tvInput.setText(process + "×");
}
});
btnDivision.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
process = tvInput.getText().toString();
tvInput.setText(process + "÷");
}
});
btnDot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
process = tvInput.getText().toString();
tvInput.setText(process + ".");
}
});
btnPercent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
process = tvInput.getText().toString();
tvInput.setText(process + "%");
}
});
btnBracket.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkBracket){
process = tvInput.getText().toString();
tvInput.setText(process + ")");
checkBracket = false;
}else{
process = tvInput.getText().toString();
tvInput.setText(process + "(");
checkBracket = true;
}
}
});
btnBackspace.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String str=tvInput.getText().toString();
if (str.length() >=1 ) {
str = str.substring(0, str.length() - 1);
tvInput.setText(str);
} else if (str.length() <=1 ) {
tvInput.setText("0");
}
}
});
btnEqual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
process = tvInput.getText().toString();
process = process.replaceAll("×","*");
process = process.replaceAll("%","/100");
process = process.replaceAll("÷","/");
Context rhino = Context.enter();
rhino.setOptimizationLevel(-1);
String finalResult = "";
try {
Scriptable scriptable = rhino.initStandardObjects();
finalResult = rhino.evaluateString(scriptable,process,"javascript",1,null).toString();
}catch (Exception e){
finalResult="0";
}
tvOutput.setText(finalResult);
}
});
}
}
Any help would be appreciated.
Thank you.
There could be other solutions to your problem. I am proposing this one.
Put an if() condition to check if the answer is whole number or not.
if(result == (int)result){
DecimalFormat df = new DecimalFormat("0")
return df.format(result);
}
return result;
You can check if it is a whole number or not by simply doing this:
if (finalResult % 1 == 0){
//then the finalResult is a whole number.
}
package com.deitel.calculator;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
double input1 = 0, input2 = 0d ,count=0;
Button btn0, btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn_dot, btn_equal, btn_subtract, btn_multi, btn_add, btn_devision, btn_clear, btn_back;
TextView text_result;
boolean Addition, Subtraction, Multiplication, Devision, decimal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn0 = findViewById(R.id.btn0);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
btn3 = findViewById(R.id.btn3);
btn4 = findViewById(R.id.btn4);
btn5 = findViewById(R.id.btn5);
btn6 = findViewById(R.id.btn6);
btn7 = findViewById(R.id.btn7);
btn8 = findViewById(R.id.btn8);
btn9 = findViewById(R.id.btn9);
btn_dot = findViewById(R.id.btn_dot);
btn_equal = findViewById(R.id.btn_equal);
btn_add = findViewById(R.id.btn_add);
btn_subtract = findViewById(R.id.btn_subtract);
btn_multi = findViewById(R.id.btn_multi);
btn_devision = findViewById(R.id.btn_devision);
btn_clear = findViewById(R.id.btn_clear);
btn_back = findViewById(R.id.btn_back);
text_result = findViewById(R.id.text_result);
btn0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "0");
}
});
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "1");
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "2");
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "3");
}
});
btn4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "4");
}
});
btn5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "5");
}
});
btn6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "6");
}
});
btn7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "7");
}
});
btn8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "8");
}
});
btn9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "9");
}
});
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Addition = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_subtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Subtraction = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_multi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Multiplication = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_devision.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Devision = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText("");
input1 = 0.0;
input1 = 0.0;
}
});
btn_dot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(count==0){
count=1;
text_result.setText(text_result.getText()+".");
return;
}
else{
text_result.setText(text_result.getText()+"0.");
decimal=true;
}
}
});
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String number = text_result.getText().toString();
int input = number.length();
if (input > 0) {
text_result.setText(number.substring(0, input - 1));
}
}
});
btn_equal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count=0;
if ((Addition || Subtraction || Multiplication || Devision) ) {
if (text_result.getText().toString().trim().equals("")){
input2=0;
return;
}else {
input2 = Float.parseFloat(text_result.getText() + "");
}
}
if (Addition) {
text_result.setText(input1 + input2 + "");
Addition = false;
}
if (Subtraction) {
text_result.setText(input1 - input2 + "");
Subtraction = false;
}
if (Multiplication) {
text_result.setText(input1 * input2 + "");
Multiplication = false;
}
if (Devision) {
text_result.setText(input1 / input2 + "");
Devision = false;
}
}
});
}
}
When I press dot button I want that dot button press only one time in input 1 like:2.5+3.7 etc.
But this code doesn't meet that requirements - it displays 2.3.4.5 etc..but I want only one dot in one input. When I press dot button I want that dot button press only one time in input 1 like:2.5+3.7 etc.
Here you can manage that with simple flag.
public class MainActivity extends AppCompatActivity {
// IDs of all the numeric buttons
private int[] numericButtons = {R.id.btnZero, R.id.btnOne, R.id.btnTwo, R.id.btnThree, R.id.btnFour, R.id.btnFive, R.id.btnSix, R.id.btnSeven, R.id.btnEight, R.id.btnNine};
// IDs of all the operator buttons
private int[] operatorButtons = {R.id.btnAdd, R.id.btnSubtract, R.id.btnMultiply, R.id.btnDivide};
// TextView used to display the output
private TextView txtScreen;
// Represent whether the lastly pressed key is numeric or not
private boolean lastNumeric;
// Represent that current state is in error or not
private boolean stateError;
// If true, do not allow to add another DOT
private boolean lastDot;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the TextView
this.txtScreen = (TextView) findViewById(R.id.txtScreen);
// Find and set OnClickListener to numeric buttons
setNumericOnClickListener();
// Find and set OnClickListener to operator buttons, equal button and decimal point button
setOperatorOnClickListener();
}
/**
* Find and set OnClickListener to numeric buttons.
*/
private void setNumericOnClickListener() {
// Create a common OnClickListener
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Just append/set the text of clicked button
Button button = (Button) v;
if (stateError) {
// If current state is Error, replace the error message
txtScreen.setText(button.getText());
stateError = false;
} else {
// If not, already there is a valid expression so append to it
txtScreen.append(button.getText());
}
// Set the flag
lastNumeric = true;
}
};
// Assign the listener to all the numeric buttons
for (int id : numericButtons) {
findViewById(id).setOnClickListener(listener);
}
}
/**
* Find and set OnClickListener to operator buttons, equal button and decimal point button.
*/
private void setOperatorOnClickListener() {
// Create a common OnClickListener for operators
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// If the current state is Error do not append the operator
// If the last input is number only, append the operator
if (lastNumeric && !stateError) {
Button button = (Button) v;
txtScreen.append(button.getText());
lastNumeric = false;
lastDot = false; // Reset the DOT flag
}
}
};
// Assign the listener to all the operator buttons
for (int id : operatorButtons) {
findViewById(id).setOnClickListener(listener);
}
// Decimal point
findViewById(R.id.btnDot).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (lastNumeric && !stateError && !lastDot) {
txtScreen.append(".");
lastNumeric = false;
lastDot = true;
}
}
});
// Clear button
findViewById(R.id.btnClear).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtScreen.setText(""); // Clear the screen
// Reset all the states and flags
lastNumeric = false;
stateError = false;
lastDot = false;
}
});
// Equal button
findViewById(R.id.btnEqual).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onEqual();
}
});
}
/**
* Logic to calculate the solution.
*/
private void onEqual() {
// If the current state is error, nothing to do.
// If the last input is a number only, solution can be found.
if (lastNumeric && !stateError) {
// Read the expression
String txt = txtScreen.getText().toString();
// Create an Expression (A class from exp4j library)
Expression expression = new ExpressionBuilder(txt).build();
try {
// Calculate the result and display
double result = expression.evaluate();
txtScreen.setText(Double.toString(result));
lastDot = true; // Result contains a dot
} catch (ArithmeticException ex) {
// Display an error message
txtScreen.setText("Error");
stateError = true;
lastNumeric = false;
}
}
}
}
I making a simple app in android studio. I have used a Single textview to take in both numbers. I also have buttons made, for the 10 digits, 4 operations and decimal point, and equals.
My app does not read the second number. When I press '=' button, it just displays the first number.
For example, when I put in a number 25, and I press the '+' button, the number gets stored in a float variable res, and the textview is cleared. Now if I put in a second number 11 and I press '=', the output is 25.0
Below, is my code for when I press the + button.
sum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(result.getText()==null)
{
result.setText("");
}
else
{
num1 = Float.parseFloat(result.getText().toString());
res=res+num1;
result.setText(null);
num1=0;
}
}
});
and below is my code when I press =
equal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(Float.toString(res));
res=0;
}
});
num1 and res, both are float, both initialized to 0.
Edit:- adding the full java code.
public class Calculator extends AppCompatActivity {
TextView result;
Button one,two,three,four,five,six,seven,eight,nine,zero,sum,sub,mul,div,decimal,equal;
float num1,num2,res=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
result = findViewById(R.id.result);
one = findViewById(R.id.button_one);
two = findViewById(R.id.button_two);
three = findViewById(R.id.button_three);
four = findViewById(R.id.button_four);
five = findViewById(R.id.button_five);
six = findViewById(R.id.button_six);
seven = findViewById(R.id.button_seven);
eight = findViewById(R.id.button_eight);
nine = findViewById(R.id.button_nine);
zero = findViewById(R.id.button_zero);
sum = findViewById(R.id.button_add);
sub = findViewById(R.id.button_sub);
mul = findViewById(R.id.button_mul);
div = findViewById(R.id.button_div);
decimal = findViewById(R.id.button_decimal);
equal = findViewById(R.id.button_equal);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(result.getText() + "1");
}
});
two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(result.getText() + "2");
}
});
three.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(result.getText() + "3");
}
});
four.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(result.getText() + "4");
}
});
five.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(result.getText() + "5");
}
});
six.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(result.getText() + "6");
}
});
seven.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(result.getText() + "7");
}
});
eight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(result.getText() + "8");
}
});
nine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(result.getText() + "9");
}
});
zero.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(result.getText() + "0");
}
});
decimal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(result.getText() + ".");
}
});
sum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(result.getText()==null)
{
result.setText("");
}
else
{
num1 = Float.parseFloat(result.getText().toString());
res=res+num1;
result.setText(null);
num1=0;
}
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(result.getText()==null)
{
result.setText("");
}
else
{
num1 = Float.parseFloat(result.getText() + "");
res=res-num1;
result.setText(null);
}
}
});
mul.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(result.getText()==null)
{
result.setText("");
}
else
{
num1 = Float.parseFloat(result.getText() + "");
res=res/num1;
result.setText(null);
}
}
});
div.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(result.getText()==null)
{
result.setText("");
}
else
{
num1 = Float.parseFloat(result.getText() + "");
res=res/num1;
result.setText(null);
}
}
});
equal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(Float.toString(res));
res=0;
}
});
}
}
Your should also take the second value from the user and make the calculations in every operator function respectively.
There is logical error in your all the operators functions.
Your should add this line in all the operator whenever the specific function in called.
result.setText(num1 - num2 + "");
result.setText(num1 + num2 + "");
and so on!!!
Your are using a wrong technique by making anonymous function for the operation. Please you switch statement of nested if-else.
You are not reading in the value for the second number (right of the operator). Your OnClickListener for the = button does nothing but display res. It doesn't apply the right hand of the operator i.e. the second number
E.g. 1 + 2 = 3
Step 1 press 1
Step 2 press +, the program will get the left of the operator and load it to num1 and add it to res.
Step 3 press 2
Step 4 press =, the program will display res
If you want to see what your program is doing in real time then try using the "Debug" tool where you will be able to step through the program line by line and see what variables are being set to what extra.
use switch case for operators,
let say following are fields;
public static final int plus = 1
public static final int minus= 2
public static final int divide= 3
public static final int multiply= 4
and a variable that hold the current operation,
int currentOperation;
and when some operator button clicked then assign "currentOperation" to that operation
in listener
sum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(result.getText()==null)
{
result.setText("");
}
else
{
num1 = Float.parseFloat(result.getText().toString());
res=res+num1;
result.setText(null);
num1=0;
currentOperation = plus //plus is public static final int plus = 1
}
}
});
and update '=' lisetener with switch statement,
equal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
num1 = Float.parseFloat(result.getText().toString());
switch(currentOperation){
case plus:
res=res+num1;
break;
case minus:
res=res-num1;
break;
case divide:
res=res/num1;
break;
case multiply:
res=res*num1;
break;
}
result.setText(""+ res);
num1=0;
}
});
I want to create a sound by comparing longitude and latitude with a value when value is 0. I tried this with infinite loop without thread. But the program crashed. Then I tried with thread, but it also failed.
public class MainActivity extends Activity
{
Button start,exit;
GPSTracker gps;
MediaPlayer audio1;
Boolean button;
TextView txt1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start=(Button)findViewById(R.id.button1);
exit=(Button)findViewById(R.id.button2);
txt1=(TextView)findViewById(R.id.textView1);
audio1=MediaPlayer.create(MainActivity.this,R.raw.audio);
button=false;
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(button==true)
{
button=false;
start.setText("START");
txt1.setText("Press 'START' to start working");
audio1.pause();
}
else
{
button=true;
start.setText("STOP");
txt1.setText("Press 'STOP' to stop working");
gps= new GPSTracker(MainActivity.this);
if(gps.canGetLoc())
{
double latitude= gps.getLatitude();
double longitude=gps.getLongitude();
if(latitude!=0&&longitude!=0)
{
audio1.start();
}
else
Toast.makeText(getApplicationContext(), "Wait for some seconds...", Toast.LENGTH_SHORT).show();
}
else
{
gps.showSettingsAlert();
}
}
}
});
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
audio1.stop();
finish();
}
});
}
alright so im making an android app, and basically everything is working fine expect the whole part about changing the status textview everytime "moneynum" is increased by 100. Heres my code:
package life.project;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ViewFlipper;
public class LifeActivity extends Activity {
/** Called when the activity is first created. */
ViewFlipper views;
int lifestatus=0;
TextView status;
Button main;
Button work;
TextView timer;
int moneynum=0;
int test=0;
Button GasStation;
Button Walmart;
Button Business;
TextView Moneycount;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
main=(Button) findViewById(R.id.button9);
views=(ViewFlipper) findViewById(R.id.viewFlipper1);
GasStation=(Button) findViewById(R.id.button13);
Walmart=(Button) findViewById(R.id.button23);
Business=(Button) findViewById(R.id.button33);
Moneycount=(TextView) findViewById(R.id.textView);
timer=(TextView) findViewById(R.id.textView3);
status=(TextView) findViewById(R.id.textView4);
work=(Button) findViewById(R.id.button1);
new CountDownTimer(1200000, 60000) {
public void onTick(long millisUntilFinished) {
timer.setText("Minutes remaining: " + millisUntilFinished / 60000);
}
public void onFinish() {
onPause();{
Intent timerends=new Intent("com.life.project.timesup");
startActivity(timerends);
finish();
}
}
}.start();
main.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
views.showPrevious();
}
});
work.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
views.showNext();
}
});
GasStation.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
moneynum+=5;
Moneycount.setText("Money:$ "+moneynum+" .00");
if(moneynum==moneynum+100){
lifestatus+=1;
status.setText("Status: "+lifestatus);
}
}
});
Walmart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
moneynum+=10;
Moneycount.setText("Money:$ "+moneynum+" .00");
if(moneynum==moneynum+100){
lifestatus+=1;
status.setText("Status: "+lifestatus);
}
}
});
Business.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
moneynum+=20;
Moneycount.setText("Money:$ "+moneynum+" .00");
if(moneynum==moneynum+100){
lifestatus+=1;
status.setText("Status: "+lifestatus);
}
}
});
}
}
and heres the part where its not working:
Moneycount.setText("Money:$ "+moneynum+" .00");
if(moneynum==moneynum+100){
lifestatus+=1;
status.setText("Status: "+lifestatus);
}
so everytime moneynum is increased by 100 i want lifestatus to increase by one and go through the rest of the code. But the if statement isnt executing when i run the program, and i think its because i have the arguments of the if statement wrong..can someone figure out i could make this work? sorry if this is confusing.
public .... LifeActivity
{
int moneySum = 100;
....
....
}
public void moneyCount()
{
if(moneynum>=moneySum) // Morethan incase your using looking for when moneynum passes 100 mark not when it equal exactly 100
{
lifestatus+=1;
status.setText("Status: "+lifestatus);
moneySum+=100;
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
moneynum+=20;
Moneycount.setText("Money:$ "+moneynum+" .00");
moneyCount();