I'm making a simple android calculator that has to support +,-,*,/ .
When I try to press any button - the app crashes. After some investigations, I found out that the problem is in the inner if statement :
public void buttonFunctionNumber(View view) {
if (view instanceof Button){
Button button = (Button) view;
String str = button.getText().toString();
if (Double.parseDouble(result.getText().toString()) == 0)
result.setText(str);
else
result.append(str);
}
}
The if: after the user pressed the desired number, and right before he prasses the second - the calculator's screen will show a 0. So in this if I want to check whether the result is 0 (the result is what the calculator's screen shows) to know that the user want to continue to the next number.
the else: the user wants to continue adding more digits to the number for the calculations so we append the next digit.
I would like to know how can I solve this problem.
Thanks for your time :)
The whole code:
package com.example.myfirstproj;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
TextView result;
double num1=0.0, num2=0.0;
String sign = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = findViewById(R.id.textViewResult);
}
public void buttonFunctionNumber(View view) {
if (view instanceof Button){
Button button = (Button) view;
String str = button.getText().toString();
if (Double.parseDouble(result.getText().toString()) == 0.0)
result.setText(str);
else
result.append(str);
}
}
public void buttonEqualFunction(View view) {
if (view instanceof Button) {
String temp2 = result.getText().toString();
num2 = Double.parseDouble(temp2);
double res = 0.0;
switch (sign) {
case "+":
res = num1 + num2;
break;
case "-":
res = num1 - num2;
break;
case "*":
res = num1 * num2;
break;
case "/":
if (num2 != 0.0)
res = num1 / num2;
else
Toast.makeText(this, "Error Cant divide by 0", Toast.LENGTH_LONG).show();
break;
default:
break;
}
num1 = res;
result.setText(res + "");
}
}
public void buttonAddFunction(View view) {
if (view instanceof Button){
String temp1 = result.getText().toString();
num1 = Double.parseDouble(temp1);
sign = "+";
result.setText(" ");
}
}
public void buttonSubtractFunction(View view) {
if (view instanceof Button) {
String temp1 = result.getText().toString();
num1 = Double.parseDouble(temp1);
sign = "-";
result.setText("0");
}
}
public void buttonMultiplyFunction(View view) {
if (view instanceof Button) {
String temp1 = result.getText().toString();
num1 = Double.parseDouble(temp1);
sign = "*";
result.setText("0");
}
}
public void buttonDivideFunction(View view) {
if (view instanceof Button) {
String temp1 = result.getText().toString();
num1 = Double.parseDouble(temp1);
sign = "/";
result.setText("0");
}
}
public void buttonClearFunction(View view) {
result.setText("0");
}
}
Try trimming your result and checking for null and empty first before parsing
String result = result.getText().toString()).trim();
if (result != null && result.length() > 0) {
if (Double.parseDouble(result) == 0.0)
result.setText(str);
else
result.append(str);
}
Related
I've been working on a little project, and I had a problem in implementing my idea. The app I'm trying to build is an educational app that gives random basic math (+,-,*,/) question, if the student got it right, it should show the next question, otherwise, it should give him/her another chance to try again.
My problem falls specifically in the last part, I wrote a function to show the next question, but I don't exactly know how to call it when the button is clicked.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import java.util.Random;
import static java.lang.String.valueOf;
public class MainActivity extends AppCompatActivity {
TextView fN;
TextView sN;
TextView oP;
TextView out;
TextView ht;
EditText ans;
Button btn;
int answer;
int fNum;
int sNum;
int opNum;
Random r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ht.setVisibility(View.GONE);
final String[] ops = {"+","-","÷","×"};
final String[] pass = {
"Very good!",
"Excellent!",
"Nice work!",
"Keep up the good work!"
};
final String[] fail = {
"No. Please try again.",
"Wrong. Try once more.",
"Don't give up!",
"No. Keep trying."
};
public static void nextQ() {
//UI variables
fN = findViewById(R.id.fN);
sN = findViewById(R.id.sN);
oP = findViewById(R.id.oP);
out = findViewById(R.id.out);
ans = findViewById(R.id.Ans);
btn = findViewById(R.id.btn);
//functionalities variables
r = new Random();
fNum = r.nextInt(9);
sNum = r.nextInt(9);
opNum = r.nextInt(ops.length);
if (opNum == 0)
answer = fNum + sNum;
if (opNum == 1)
answer = fNum - sNum;
if (opNum == 2)
answer = fNum / sNum;
if (opNum == 3)
answer = fNum * sNum;
ht.setText(answer);
}
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ht = findViewById(R.id.hText);
fN.setText(fNum);
sN.setText(sNum);
oP.setText(ops[opNum]);
int usrAns = Integer.parseInt(valueOf(ans.getText()));
int rMSG = r.nextInt(pass.length);
if(answer == usrAns)
out.setText(""+pass[rMSG]);
nextQ();
if(answer != usrAns)
out.setText(""+fail[rMSG]);
}
});
}
}
Try to put this code & check whether it works or not?
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
import static java.lang.String.valueOf;
public class MainActivity extends AppCompatActivity {
TextView fN;
TextView sN;
TextView oP;
TextView out;
TextView ht;
EditText ans;
Button btn;
int answer;
int fNum;
int sNum;
int opNum;
Random r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ht.setVisibility(View.GONE);
btn = findViewById(R.id.btn);
fN = findViewById(R.id.fN);
sN = findViewById(R.id.sN);
oP = findViewById(R.id.oP);
out = findViewById(R.id.out);
ans = findViewById(R.id.Ans);
final String[] ops = {"+", "-", "÷", "×"};
final String[] pass = {
"Very good!",
"Excellent!",
"Nice work!",
"Keep up the good work!"
};
final String[] fail = {
"No. Please try again.",
"Wrong. Try once more.",
"Don't give up!",
"No. Keep trying."
};
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ht = findViewById(R.id.hText);
fN.setText(fNum);
sN.setText(sNum);
oP.setText(ops[opNum]);
int usrAns = Integer.parseInt(valueOf(ans.getText()));
int rMSG = r.nextInt(pass.length);
if (answer == usrAns)
out.setText("" + pass[rMSG]);
nextQ();
if (answer != usrAns)
out.setText("" + fail[rMSG]);
}
});
}
public void nextQ() {
//functionalities variables
r = new Random();
fNum = r.nextInt(9);
sNum = r.nextInt(9);
opNum = r.nextInt(ops.length);
if (opNum == 0)
answer = fNum + sNum;
if (opNum == 1)
answer = fNum - sNum;
if (opNum == 2)
answer = fNum / sNum;
if (opNum == 3)
answer = fNum * sNum;
ht.setText(answer);
}
}
Remove static from function nextQ(). And also remove it from onCreate(). put it outside on onCreate().
Function will look like:
onCreate(){ ... }
public void nextQ() {
....
}
Call it like
MainActivity.this.nextQ();
Remove below code form nextQ() and put in onCreate() method:
fN = findViewById(R.id.fN);
sN = findViewById(R.id.sN);
oP = findViewById(R.id.oP);
out = findViewById(R.id.out);
ans = findViewById(R.id.Ans);
btn = findViewById(R.id.btn);
I'm new in programming and I need your help, I have a error when insert number in editText txt50, app crashes please help me, I don't know what is the error:
code:
public class Main2Activity extends AppCompatActivity {
private EditText cinco, cien, doscientos, quinientos, mil, dosmil, cincomil, diezmil, veintemil, cincuentamil, cienmil;
private TextView diezmob;
public static final String nombres = "names";
TextView txtBienvenido;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
txtBienvenido = (TextView) findViewById(R.id.txtbienvenido);
String usuario = getIntent().getStringExtra("names");
txtBienvenido.setText("¡Bienvenido(a) Hermano(a) " + usuario + "!");
diezmob = (TextView) findViewById(R.id.txtdiezmob);
cinco = (EditText) findViewById(R.id.txt50);
cien = (EditText) findViewById(R.id.txt100);
doscientos = (EditText) findViewById(R.id.txt200);
quinientos = (EditText) findViewById(R.id.txt500);
mil = (EditText) findViewById(R.id.txt1000);
dosmil = (EditText) findViewById(R.id.txt2000);
cincomil = (EditText) findViewById(R.id.txt5000);
diezmil = (EditText) findViewById(R.id.txt10000);
veintemil = (EditText) findViewById(R.id.txt20000);
cincuentamil = (EditText) findViewById(R.id.txt50000);
cienmil = (EditText) findViewById(R.id.txt100000);
cinco.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if ((cinco.toString().equals("")) && (!cinco.toString().equals(null)) && (cinco.toString().isEmpty() || (cinco.toString().length() >= 0))) {
double valor1 = Double.parseDouble((cinco.getText().toString()));
double valor2 = Double.parseDouble((cien.getText().toString()));
double valor3 = Double.parseDouble((doscientos.getText().toString()));
double valor4 = Double.parseDouble((quinientos.getText().toString()));
double valor5 = Double.parseDouble((mil.getText().toString()));
double valor6 = Double.parseDouble((dosmil.getText().toString()));
double valor7 = Double.parseDouble((cincomil.getText().toString()));
double valor8 = Double.parseDouble((diezmil.getText().toString()));
double valor9 = Double.parseDouble((veintemil.getText().toString()));
double valor10 = Double.parseDouble((cincuentamil.getText().toString()));
double valor11 = Double.parseDouble((cienmil.getText().toString()));
double suma = (valor1 * 50) + (valor2 * 100) + (valor3 * 200) + (valor4 * 500) + (valor5 * 1000) + (valor6 * 2000) + (valor7 * 5000) + (valor8 * 10000) + (valor9 * 20000) + (valor10 * 50000) + (valor11 * 100000);
String resultado = String.valueOf((int) suma);
diezmob.setText(String.valueOf(resultado));
} else {
diezmob.setText("0");
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
} }
LogCat: Error when insert number in editText txt50, the app crashes:
java.lang.NumberFormatException: Invalid double: ""
I resolve this error with this code, any error please say it.
package com.example.josue.login;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Calendar;
public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
private TextView diezmob;
public static final String nombres = "names";
TextView txtBienvenido;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
txtBienvenido = (TextView) findViewById(R.id.txtbienvenido);
String usuario = getIntent().getStringExtra("names");
txtBienvenido.setText("¡Bienvenido(a) Hermano(a) " + usuario + "!");
diezmob = (TextView) findViewById(R.id.txtdiezmob);
findViewById(R.id.btncalcular).setOnClickListener(this);
findViewById(R.id.btncalcular5).setOnClickListener(this);
findViewById(R.id.btncalcular10).setOnClickListener(this);
findViewById(R.id.btncalcular15).setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btncalcular:
double cinco, cien, doscientos, quinientos, mil, dosmil, cincomil, diezmil, veintemil, cincuentamil, cienmil;
String Cinco = ((EditText) findViewById(R.id.txt50)).getText().toString();
String Cien = ((EditText) findViewById(R.id.txt100)).getText().toString();
String Doscientos = ((EditText) findViewById(R.id.txt200)).getText().toString();
String Quinientos = ((EditText) findViewById(R.id.txt500)).getText().toString();
String Mil = ((EditText) findViewById(R.id.txt1000)).getText().toString();
String Dosmil = ((EditText) findViewById(R.id.txt2000)).getText().toString();
String Cincomil = ((EditText) findViewById(R.id.txt5000)).getText().toString();
String Diezmil = ((EditText) findViewById(R.id.txt10000)).getText().toString();
String Veintemil = ((EditText) findViewById(R.id.txt20000)).getText().toString();
String Cincuentamil = ((EditText) findViewById(R.id.txt50000)).getText().toString();
String Cienmil = ((EditText) findViewById(R.id.txt100000)).getText().toString();
if (Cinco != null && !Cinco.equals("")) {
cinco = Double.valueOf(Cinco);
}else{
cinco = 0;
}
if (Cien != null && !Cien.equals("")){
cien = Double.valueOf(Cien);
}else{
cien=0;
}
if (Doscientos != null && !Doscientos.equals("")) {
doscientos = Double.valueOf(Doscientos);
}else{
doscientos=0;
}
if (Quinientos != null && !Quinientos.equals("")) {
quinientos = Double.valueOf(Quinientos);
}else{
quinientos = 0;
}
if (Mil != null && !Mil.equals("")){
mil = Double.valueOf(Mil);
}else{
mil = 0;
}
if (Dosmil != null && !Dosmil.equals("")) {
dosmil = Double.valueOf(Dosmil);
}else {
dosmil = 0;
}
if (Cincomil != null && !Cincomil.equals("")) {
cincomil = Double.parseDouble(Cincomil);
}else {
cincomil = 0;
}
if (Diezmil !=null && !Diezmil.equals("")) {
diezmil = Double.valueOf(Diezmil);
}else {
diezmil = 0;
}
if (Veintemil != null && !Veintemil.equals("")) {
veintemil = Double.valueOf(Veintemil);
}else {
veintemil = 0;
}
if (Cincuentamil != null && !Cincuentamil.equals("") ) {
cincuentamil = Double.valueOf(Cincuentamil);
}else {
cincuentamil = 0;
}
if (Cienmil != null && !Cienmil.equals("") ) {
cienmil = Double.valueOf(Cienmil);
}else {
cienmil = 0;
}
double suma = (cinco * 50) + (cien * 100) + (doscientos * 200) + (quinientos * 500) + (mil * 1000) +
(dosmil * 2000) + (cincomil * 5000) + (diezmil * 10000) + (veintemil * 20000) + (cincuentamil * 50000) +
(cienmil * 100000);
String resultado = String.valueOf((int)(suma));
diezmob.setText(String.valueOf(resultado));
break;
case R.id.btncalcular5:
Intent i = new Intent(this, Main5Activity.class);
i.putExtra("dato",diezmob.getText().toString());
startActivity(i);
break;
case R.id.btncalcular10:
Intent ii = new Intent(this, Main5Activity.class);
startActivity(ii);
break;
case
R.id.btncalcular15:
Intent iii = new Intent(this, Main5Activity.class);
startActivity(iii);
break;
default:
break;
}
}
}
Let's evaluate this:
if ((cinco.toString().equals("")) && (!cinco.toString().equals(null)) && (cinco.toString().isEmpty() || (cinco.toString().length() >= 0))) {
double valor1 = Double.parseDouble((cinco.getText().toString()));
You are saying if ("cinco is an empty string") and (not null) and ((isEmpty(same as empty string)) or is a length >= 0) then parse double
I am pretty sure the only time this evaluates to true is if cinco is empty which will result in a NumberFormatException because you are trying to parse cinco for a double while it is empty. You will have to handle exceptions with a try-catch block:
try {
double valor1 = Double.parseDouble((cinco.getText().toString()));
} catch (NumberFormatException e) {
e.printStackTrace();
}
or construct if statements that don't allow cinco to be evaluated if it is empty:
if(cinco.toString() != null && !(cinco.toString().isEmpty() {
double valor1 = Double.parseDouble((cinco.getText().toString()));
}
edit: All of the Double.parseDouble in your code will throw NumberFormatExceptions not just cinco by the way. That one is just first so this answer applies to all of the parses.
I'm Mikamocha, and I just started programming Android apps. I have problems in my first calculator app (the results). What I mean is so that 2+2 will be 4 instead of 4.0, 5-2 will be 3 instead of 3.0, etc.
package com.yeshua.mikamocha.myxcalculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText Scr;
private float NumberBf=0, NumAf, result=0;
private String Operation, mod="replace";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Scr = (EditText) findViewById(R.id.txtScreen);
Scr.setText("");
int idList[] = {R.id.btn0, R.id.btn1, R.id.btn2, R.id.btn2, R.id.btn3, R.id.btn4,
R.id.btn5, R.id.btn6, R.id.btn7, R.id.btn8, R.id.btn9,
R.id.btnAdd, R.id.btnSubtract, R.id.btnMultiply, R.id.btnDivide,
R.id.btnClear,R.id.btnEquals, R.id.btnDot, };
for(int id:idList) {
View v = (View) findViewById(id);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onButtonClick(v);
}
});
}
}
public void mMath(String str) {
mResult();
try {
NumberBf = Float.parseFloat(Scr.getText().toString());
Operation = str;
}catch (Exception e) {
Toast.makeText(getApplicationContext(), (CharSequence) e, Toast.LENGTH_SHORT).show();
Scr.setText("SYNTAX ERROR");
mod = "replace";
}
}
public void mResult() {
NumAf = 0;
if(!Scr.getText().toString().trim().isEmpty())
NumAf = Float.parseFloat(Scr.getText().toString());
result = NumAf;
try {
switch (Operation) {
case "+":
result = NumAf + NumberBf;
break;
case "-":
result = NumberBf - NumAf;
break;
case "*":
result = NumAf * NumberBf;
break;
case "/":
result = NumberBf / NumAf;
break;
default:
result = NumAf;
break;
}
} catch (Exception e) {
e.printStackTrace();
}
Scr.setText(String.valueOf(result));
mod = "replace";
}
public void getKeyboard(String str) {
String ScrTxt = Scr.getText().toString();
ScrTxt += str;
if(mod.equals("add"))
Scr.setText(ScrTxt);
else
Scr.setText(str);
mod = "add";
}
public void onButtonClick(View v) {
switch (v.getId()) {
case R.id.btnClear: //Clear
Scr.setText("");
NumberBf = 0;
Operation = "";
break;case R.id.btnAdd:
mMath("+");
break;
case R.id.btnSubtract:
if(mod.equals("replace")) {
String numb = ((Button) v).getText().toString();
getKeyboard(numb);
}
else mMath("-");
break;
case R.id.btnMultiply:
mMath("*");
break;
case R.id.btnDivide:
mMath("/");
break;
case R.id.btnEquals:
mResult();
Operation = "";
NumberBf = 0;
break;
default:
String numb = ((Button) v).getText().toString();
getKeyboard(numb);
break;
}
}
}
Thanks.
You should use NumberFormat.
For example:
public static void main(String[] args) {
System.out.println(format(14.0184849945)); // prints '14.01'
System.out.println(format(13)); // prints '13'
System.out.println(format(3.5)); // prints '3.5'
System.out.println(format(3.138136)); // prints '3.13'
}
public static String format(Number n) {
NumberFormat format = DecimalFormat.getInstance();
format.setRoundingMode(RoundingMode.FLOOR);
format.setMinimumFractionDigits(0);
format.setMaximumFractionDigits(2);
return format.format(n);
}
you are using float datatype for result instead of use int type and parse operation value in int.
result = (int)(NumAf + NumberBf);
For Ref. DecimalFormat
Change as follows as you are using float as result you are getting decimal so use int,
private int result=0;
//and
result =(int) (NumAf + NumberBf);
OR
float one= 2.0;
float two= 2.5;
//DecimalFormat format = new DecimalFormat();
//format.setDecimalSeparatorAlwaysShown(false);
DecimalFormat format=new DecimalFormat("#,###.#");
System.out.println( format.format(one) );//prints 2
System.out.println( format.format(two) );//prints 2.5
i have two arrays.
double number[] = new double[5];
char oper[] = new char[4];
in my program when user press any operator sign like +,-,*,/ the number array is taking user input for example if he is entering 345 it is taking and saving it in number[0] and [0] become [1] and also save the current operation input from user and save it in oper[0] and so on.
but i dont know how can i get the result using both arrays.
i am pasting whole code here.
package com.example.calculatortesting;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements OnClickListener {
TextView textdisplay;
EditText currentcalc;
EditText et1;
double number[] = new double[5]; //for saving numbers in array
char oper[] = new char[4]; //for saving operation in array
int numposition = 0; //for position of number array
int operposition = 0; //for position of operation array
double currentnum; //saving current number before operation
int last_button = 0; //checking last button pressed
char operator; //saving pressed operation value
String newnum = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculator);
et1 = (EditText) findViewById(R.id.editText1);
textdisplay = (TextView) findViewById(R.id.editText1);
currentcalc = (EditText) findViewById(R.id.textView1);
Button b1 = (Button) findViewById(R.id.b1);
Button b2 = (Button) findViewById(R.id.b2);
Button b3 = (Button) findViewById(R.id.b3);
Button b4 = (Button) findViewById(R.id.b4);
Button b5 = (Button) findViewById(R.id.b5);
Button b6 = (Button) findViewById(R.id.b6);
Button b7 = (Button) findViewById(R.id.b7);
Button b8 = (Button) findViewById(R.id.b8);
Button b9 = (Button) findViewById(R.id.b9);
Button b0 = (Button) findViewById(R.id.b0);
Button multiply1 = (Button) findViewById(R.id.multiply);
Button divide1 = (Button) findViewById(R.id.divide);
Button plus1 = (Button) findViewById(R.id.plus);
Button minus1 = (Button) findViewById(R.id.minus);
Button equal1 = (Button) findViewById(R.id.equal);
Button clear1 = (Button) findViewById(R.id.clear);
Button back1 = (Button) findViewById(R.id.backspace);
Button dot1 = (Button) findViewById(R.id.decimal);
Button plusminus1 = (Button) findViewById(R.id.plusminus);
Button percent = (Button) findViewById(R.id.percent);
Button shift = (Button) findViewById(R.id.shift);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
b4.setOnClickListener(this);
b5.setOnClickListener(this);
b6.setOnClickListener(this);
b7.setOnClickListener(this);
b8.setOnClickListener(this);
b9.setOnClickListener(this);
b0.setOnClickListener(this);
multiply1.setOnClickListener(this);
divide1.setOnClickListener(this);
plus1.setOnClickListener(this);
minus1.setOnClickListener(this);
equal1.setOnClickListener(this);
clear1.setOnClickListener(this);
back1.setOnClickListener(this);
dot1.setOnClickListener(this);
plusminus1.setOnClickListener(this);
percent.setOnClickListener(this);
shift.setOnClickListener(this);
}
public void currentcalcmethod(String currentcalcoper) {
currentcalc.setText(currentcalc.getText() + currentcalcoper);
currentcalc.setSelection(currentcalc.getText().length());
}
void number() {
}
void oper() {
number[numposition] = currentnum;
oper[operposition] = operator;
numposition ++;
operposition++;
currentnum= 0;
}
void result (){
double total;
StringBuilder builder = new StringBuilder();
for (double num : number) {
for (char op : oper){
builder.append(num + op);
total = num+op;
et1.setText(Double.toString(total));
}}
}
public void shownum(String number) {
newnum = newnum + number ;
currentnum = Double.parseDouble(newnum);
et1.setText(Double.toString(currentnum));
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.b0) {
currentcalcmethod("0");
shownum("0");
} else if (v.getId() == R.id.b1) {
currentcalcmethod("1");
shownum("1");
} else if (v.getId() == R.id.b2) {
currentcalcmethod("2");
shownum("2");
} else if (v.getId() == R.id.b3) {
currentcalcmethod("3");
shownum("3");
} else if (v.getId() == R.id.b4) {
currentcalcmethod("4");
shownum("4");
} else if (v.getId() == R.id.b5) {
currentcalcmethod("5");
shownum("5");
} else if (v.getId() == R.id.b6) {
currentcalcmethod("6");
shownum("6");
} else if (v.getId() == R.id.b7) {
currentcalcmethod("7");
shownum("7");
} else if (v.getId() == R.id.b8) {
currentcalcmethod("8");
shownum("8");
} else if (v.getId() == R.id.b9) {
currentcalcmethod("9");
shownum("9");
} else if (v.getId() == R.id.plus) {
currentcalcmethod("+");
operator = '+';
oper();
} else if (v.getId() == R.id.minus) {
currentcalcmethod("-");
operator = '-';
oper();
} else if (v.getId() == R.id.percent) {
currentcalcmethod("%");
operator = '%';
oper();
} else if (v.getId() == R.id.divide) {
currentcalcmethod("/");
operator = '/';
oper();
} else if (v.getId() == R.id.multiply) {
currentcalcmethod("*");
operator = '*';
oper();
} else if (v.getId() == R.id.decimal) {
currentcalcmethod(".");
} else if (v.getId() == R.id.equal) {
result ();
currentcalcmethod("=");
} else if (v.getId() == R.id.backspace) {
if (currentcalc.getText().toString().length() > 0) {
int start =0;
int end2 = currentcalc.getText().toString().length() - 1;
String newText2 = currentcalc.getText().toString()
.substring(start, end2);
currentcalc.setText(newText2);
}
} else if (v.getId() == R.id.clear) {
textdisplay.setText("");
currentcalc.setText("");
number = null;
oper = null;
numposition = 0;
operposition = 0;
} else if (v.getId() == R.id.plusminus) {
}
last_button = v.getId();
}
}
Take the user input as a String and parse it. Something like:
String userInput = "3+5";
List<Character> numbers = new ArrayList<>();
List<Character> operators = new ArrayList<>();
for (char c : userInput.toCharArray()) {
if(Character.isDigit(c)){
numbers.add(c);
}
else{
operators.add(c);
}
}
// Now loop through lists and perform the desired arthimetic operation based on operator
You could put all of the inputs into a String and convert the string to a double to get an actual equation.
String ans = Double.toString(number[0]) +
Char.toString(oper[0]) + Double.toString(number[1]); //could use a loop to enter all values != null
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript"); // build-in javascript engine allows for string equations.
try {
System.out.println(engine.eval(ans));
} catch (ScriptException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Something like that.
Hello I'm a college student studying Java. I'm working on a android application. It compiles and shows no error. However when it runs, there's a unexpected close error.
Here's my application. When you click on the calculate ws you purpose to change to this screen.
Here's my code:
package com.warhammerdicerrolleralpha;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class myMain extends Activity
{
EditText enternumberofdice;
final TextView textGenerateNumber = (TextView) findViewById(R.id.text4);
private EditText text, text2, text3;
private Button btutorial1;
int number1 = Integer.parseInt(text.getText().toString());
int number2 = Integer.parseInt(text2.getText().toString());
ImageView i = new ImageView(this);
{
i.setAdjustViewBounds(true);
}
private int myFaceValue;
int myNum;
/**
* Called when the activity is first created.
*
* #return
*/
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void go()
{
while (myNum > 0)
{
// TODO Auto-generated method stub
textGenerateNumber.setText(String.valueOf(enternumberofdice));
--myNum;
return;
}
}
public int roll()
{
int val = (int) (6 * Math.random() + 1); // Range 1-6
setValue(val);
return val;
}
{
try
{
myNum = Integer.parseInt(enternumberofdice.getText().toString());
}
catch (NumberFormatException nfe)
{
enternumberofdice.setText("Does not work");
}
}
public int getValue()
{
return myFaceValue;
}
public void setValue(int myFaceValue)
{
this.myFaceValue = myFaceValue;
}
{
switch (myFaceValue)
{
case 5:
i.setImageResource(R.drawable.dicefive);
break;
case 1:
i.setImageResource(R.drawable.diceone);
break;
case 3:
i.setImageResource(R.drawable.dicethree);
break;
case 2:
i.setImageResource(R.drawable.dicetwo);
break;
case 4:
i.setImageResource(R.drawable.dicefour);
break;
case 6:
i.setImageResource(R.drawable.dicesix);
break;
default:
i.setImageResource(R.drawable.error);
break;
}
text = (EditText) findViewById(R.id.editText1);
text2 =(EditText) findViewById(R.id.editText2);
text3 = (EditText) findViewById(R.id.editText3);
btutorial1 = (Button) findViewById(R.id.button1);
btutorial1.setOnClickListener((OnClickListener) this);
Button buttonGenerate = (Button) findViewById(R.id.button1);
enternumberofdice = (EditText) findViewById(R.id.enternumberofdice);
Button buttonGenerate2 = (Button) findViewById(R.id.battlecalculate);
buttonGenerate2.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
setContentView(R.layout.main2);
}
});
buttonGenerate.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
go();
roll();
}
});
}
public void onClick(View view)
{
switch (view.getId())
{
case R.id.button1:
if (number1 > number2)
{
text3.setText("Three and above");
return;
}
else if (number1 < number2)
{
text3.setText("Five and above");
return;
}
else if (number1 == number2)
{
text3.setText("Four and above");
return;
}
else
{
text3.setText("Not Working");
return;
}
}
}
}
Look at your stack trace, but I think it may be because of this block:
private EditText text, text2, text3;
private Button btutorial1;
int number1 = Integer.parseInt(text.getText().toString());
int number2 = Integer.parseInt(text2.getText().toString());
It looks as though you are trying to parseInt over null values. You need to specify where text, text2, text3 are in your form using similar code to:
TextView textGenerateNumber = (TextView) findViewById(R.id.text4);
Hope that helps.