This question already has answers here:
java.lang.numberformatexception: invalid double: " "
(6 answers)
Closed 6 years ago.
I’m making an app that can compute all I needed with just 1 click of a button, but its forced closing when I'm pushing the “calculate” button, can anyone help me with what I did wrong?
previous = (EditText) findViewById(R.id.editText);
present = (EditText) findViewById(R.id.editText2);
Button calculate = (Button) findViewById(R.id.calculate);
consumption = (TextView) findViewById(R.id.textView1);
basic = (TextView) findViewById(R.id.textView2);
mmp = (TextView) findViewById(R.id.textView3);
stp = (TextView) findViewById(R.id.textView4);
before = (TextView) findViewById(R.id.textView5);
penalty = (TextView) findViewById(R.id.textView6);
after = (TextView) findViewById(R.id.textView7);
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
makeCalculations();
}
});
}
private void makeCalculations() {
double n1 = Double.valueOf(previous.getText().toString());
double n2 = Double.valueOf(present.getText().toString());
double n3 = Double.valueOf(consumption.getText().toString());
double n4 = Double.valueOf(stp.getText().toString());
double n5 = Double.valueOf(mmp.getText().toString());
double n6 = Double.valueOf(penalty.getText().toString());
double n7 = Double.valueOf(before.getText().toString());
double n8 = Double.valueOf(basic.getText().toString());
consumption.setText("Your Consumption is: " + (n1 + n2));
basic.setText("Your Consumption is: " + (n3 * 280.00));
mmp.setText("Meter Maintenance Fee: " + 10.00);
stp.setText("Septage Fee: " + (n3 * 0.068) );
before.setText("On/Before Due Date: " + (n3 + n4 + n5));
penalty.setText("Penalty: " + (n3 / 10.00));
after.setText("After Due Date: " + (n6 + n7));
}
}
There is no validation. You should at least check that the string is not empty, but also maybe use a try catch in case a number is not entered. Then you could set the error text on the editText to explain that an invalid number was entered.
So you could do something like this for each double:
boolean answerOk = true;
double n1;
if (!previous.getText().toString().equals("") {
try {
n1 = Double.valueOf(previous.getText().toString());
} catch(NumberFormatException e) {
answerOk = false;
previous.setError("Invalid number");
}
} else {
answerOk = false;
previous.setError("Field is empty");
}
Only run the code at the bottom after all the double's are ok.
if (answerOk) {
// Do the other stuff here
}
Related
In my EditText I need the user to input data only from 5 to 10 decimal values.
How do I achieve this?
If the user enters the value less than 5 or greater than 10 I need to prompt the user to enter the value between 5 and 10.
package com.sabari.results;
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.TextView;
import android.widget.Toast;
public class Calculator extends AppCompatActivity {
TextView tv1;
TextView tv2;
TextView tv3;
TextView tv4;
TextView tv5;
TextView tv6;
TextView tv7;
TextView tv8;
TextView tv10;
EditText et1;
EditText et2;
EditText et3;
EditText et4;
EditText et5;
EditText et6;
EditText et7;
EditText et8;
Button b1;
Button b2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("CGPA Calculator");
setContentView(R.layout.calculator);
tv1 = (TextView) findViewById(R.id.textView);
tv2 = (TextView) findViewById(R.id.textView2);
tv3 = (TextView) findViewById(R.id.textView3);
tv4 = (TextView) findViewById(R.id.textView4);
tv5 = (TextView) findViewById(R.id.textView5);
tv6 = (TextView) findViewById(R.id.textView6);
tv7 = (TextView) findViewById(R.id.textView7);
tv8 = (TextView) findViewById(R.id.textView8);
b1 = (Button) findViewById(R.id.button);
b2 = (Button)findViewById(R.id.button2);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
et1 = (EditText) findViewById(R.id.editText);
et2 = (EditText) findViewById(R.id.editText2);
et3 = (EditText) findViewById(R.id.editText3);
et4 = (EditText) findViewById(R.id.editText4);
et5 = (EditText) findViewById(R.id.editText5);
et6 = (EditText) findViewById(R.id.editText6);
et7 = (EditText) findViewById(R.id.editText7);
et8 = (EditText) findViewById(R.id.editText8);
tv10 = (TextView) findViewById(R.id.textView10);
int n;
double no1=0, no2=0, no3=0, no4=0, no5=0, no6=0, no7=0, no8=0;
try {
no1 = Double.parseDouble(et1.getText().toString());
}catch (NumberFormatException e){
e.printStackTrace();
}
try{
no2 = Double.parseDouble(et2.getText().toString());}
catch (NumberFormatException e){
e.printStackTrace();
}
try {
no3 = Double.parseDouble(et3.getText().toString());
}catch (NumberFormatException e){
e.printStackTrace();
}
try {
no4 = Double.parseDouble(et4.getText().toString());
}catch (NumberFormatException e)
{
e.printStackTrace();
}
try{
no5 = Double.parseDouble(et5.getText().toString());
}catch (NumberFormatException e){
e.printStackTrace();
}
try{
no6 = Double.parseDouble(et6.getText().toString());
}catch (NumberFormatException e){
e.printStackTrace();
}
try {
no7 = Double.parseDouble(et7.getText().toString());
}catch (NumberFormatException e){
e.printStackTrace();
}try {
no8 = Double.parseDouble(et8.getText().toString());
}catch (NumberFormatException e){
e.printStackTrace();
}
if (no1<=0) {
n = 1;
} else if (no3<=0||et3.equals("")) {
n = 2;
} else if (no4<=0||et4.equals("")) {
n = 3;
} else if (no5<=0||et5.equals("")) {
n = 4;
} else if (no6<=0||et6.equals("")) {
n = 5;
} else if (no7<=0||et7.equals("")) {
n = 6;
} else if (no8<=0||et8.equals("")) {
n = 7;
} else {
n = 8;
}
double res = 0;
if((no1<=10)&&(no2<=10)&&(no3<=10)&&(no4<=10)&&(no5<=10)&&(no6<=10)&&(no7<=10)&&(no8<=10)) {
res = (no1 + no2 + no3 + no4 + no5 + no6 + no7 + no8) / n;
tv10.setText("Your CGPA is : " + res);
Toast.makeText(Calculator.this, "Your CGPA is : " + res, Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(Calculator.this,"Please enter a valid GPA ",Toast.LENGTH_LONG).show();
}
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
et2.setText("");
et3.setText("");
et4.setText("");
et5.setText("");
et6.setText("");
et7.setText("");
et8.setText("");
tv10.setText("Your CGPA is : ");
et1.setText("");
}
});
}
}
After you parse the double they entered, you can do an easy if statement to check if the value they entered is between 5 and 10:
if (no1 < 5 || no1 > 10)
{
// error... prompt them to enter value between 5 and 10
}
Alternatively, you can check for a correct value like so:
if (no1 >= 5 && no1 <= 10)
{
// good value
}
Also, to only allow the user to enter a float value, you can set the inputType property of your EditTexts to numberDecimal:
<EditText
...
android:inputType="numberDecimal"
... />
You can use an AlertDialog to let the user know the value they entered is incorrect.
As for your entire setup, you could make the code look a lot cleaner if you put all the EditTexts into a List/array, and all of the double values into another List. (A dictionary relating the two values would also be a good option). With this setup, your big section of 8 try-catch blocks would be reduced to:
for (int i = 0; i < editTexts.Length; i++)
{
try
{
nums[i] = Double.parseDouble(editTexts[i].getText().toString());
}
catch (NumberFormatException e)
{
e.printStackTrace();
}
}
Your block for checking if the values are between 5 and 10 would look similar, and you could have a Boolean value indicating whether or not an invalid value was found. The loop would break when one was found:
Boolean invalidFound = false;
for (int i = 0; i < nums.Length && !invalidFound; i++)
{
invalidFound = (nums[i] < 5 || nums[i] > 10);
}
if (invalidFound)
{
//error
}
else
{
// good values
}
There are many ways to set this up. Some of the other options might be cleaner, but I wanted to show you an option that was relatively easier to understand.
I'm working on a simple calculator
I'm still a beginner and don't know much about java or android
however, everytime I click on the button the app crashes!
what's wrong with the code ?
final Button btn = (Button) findViewById(R.id.btn);
final EditText ET = (EditText) findViewById(R.id.ET);
final EditText ET2 = (EditText) findViewById(R.id.ET2);
final EditText ET3 = (EditText) findViewById(R.id.ET3);
final TextView TV = (TextView) findViewById(R.id.textView4);
final TextView TV2 = (TextView) findViewById(R.id.textView5);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String et = ET.getText().toString();
String et2 = ET2.getText().toString();
String et3 = ET3.getText().toString();
for (int i = Integer.parseInt(et2); i < Integer.parseInt(et3); i++) {
try {
str = et.replace("X", "" + i);
}
catch (Exception e) {
str = et.replace("x", "" + i);
}
int rslt = Integer.parseInt(str);
TV.append( " " + i )
TV2.append( " " + rslt )
}
}
}
});
That's all codes already
this code is meant to make a table for a F(X) method like the one on the casio calculator. I may need it for school
like :
F(X) = X^2 + X*4 - 3
One problem I see is that outer try misses corresponding catch block and you do not check whether proper number is entered in Et2 and Et3. Integer.parseInt will throw an exception if provided text is not a proper number.
I am designing a basic BMI calculator and I have the calculator working, but I need to convert the calculated answer from a TextView which is a double to an integer to enable me right statements with <> operators based on the calculated answer.
How do I convert the answer from the TextView to an integer?
v.findViewById(R.id.bmi).setOnClickListener(this);
return v;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.bmi:
try {
EditText w = (EditText) getView().findViewById(R.id.w);
String value = w.getText().toString();
EditText h = (EditText) getView().findViewById(R.id.h);
String value1 = h.getText().toString();
TextView ans = (TextView) getView().findViewById(R.id.ans);
Double l1 = Double.parseDouble(value);
Double l2 = Double.parseDouble(value1);
ans.setText(Double.toString(l1 / (l2 * l2)));
}
catch (Exception e)
{
new AlertDialog.Builder(getActivity()).setNeutralButton("OK",null).setMessage("ALL FIELDS ARE REQUIRED TO COMPUTE YOUR BMI! ").show();
break;
}
}
}
}
First, The conversion is NOT from textview to int. textView aint a datatype. If you want the result in int use parseInt() method. int i = Integer.parseInt(value).
[EDIT]
Try this, this will work.
TextView tv = (TextView) findViewById(R.id.tv);
EditText et = (EditText) findViewById(R.id.et);
try {
double d = Double.valueOf(String.valueOf(et.getText()));
tv.setText(String.valueOf( (int) d));
}catch (NumberFormatException e){
Toast.makeText(MainActivity.this, "Enter valid number.", Toast.LENGTH_SHORT).show();
}
I have simplified it for your understanding. The code can still be optimized.
This question already has answers here:
Round a double to 2 decimal places [duplicate]
(13 answers)
Closed 9 years ago.
For my simple calculator, I am showing the result in a TextView, but it is always showing decimals. How can I remove them ?
This is my code :
public class MainActivity extends Activity implements OnClickListener {
EditText etNum1;
EditText etNum2;
Button btnAdd;
Button btnSub;
Button btnMult;
Button btnDiv;
TextView tvResult;
String oper = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// find the elements
etNum1 = (EditText) findViewById(R.id.etNum1);
etNum2 = (EditText) findViewById(R.id.etNum2);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnSub = (Button) findViewById(R.id.btnSub);
btnMult = (Button) findViewById(R.id.btnMult);
btnDiv = (Button) findViewById(R.id.btnDiv);
tvResult = (TextView) findViewById(R.id.tvResult);
// set a listener
btnAdd.setOnClickListener((OnClickListener) this);
btnSub.setOnClickListener(this);
btnMult.setOnClickListener(this);
btnDiv.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
double num1=0;
double num2=0;
double result=0;
// check if the fields are empty
if (TextUtils.isEmpty(etNum1.getText().toString())
|| TextUtils.isEmpty(etNum2.getText().toString())) {
return;
}
// read EditText and fill variables with numbers
num1 = Double.parseDouble(etNum1.getText().toString());
num2 = Double.parseDouble(etNum2.getText().toString());
// defines the button that has been clicked and performs the corresponding operation
// write operation into oper, we will use it later for output
switch (v.getId()) {
case R.id.btnAdd:
oper = "+";
result = num1 + num2;
break;
case R.id.btnSub:
oper = "-";
result = num1 - num2;
break;
case R.id.btnMult:
oper = "*";
result = num1 * num2;
break;
case R.id.btnDiv:
oper = "/";
result = num1 / num2;
break;
default:
break;
}
// form the output line
tvResult.setText(num1 + " " + oper + " " + num2 + " = " + result);
}
}
A non mathematical way to do it:
A short and simple method is, convert the double to string:
String text = String.valueOf(result);
Now you have the result in the string. Given that your requirement is that you don't want decimals, so split your string based on "." as a delimiter:
String str[] = text.split(".");
Now in str[0] you will have only the number part. so set it to the text view:
tvResult.setText(num1 + " " + oper + " " + num2 + " = " + str[0]);
I'm sure this one works fine.
You can use DecimalFormat to format the result:
DecimalFormat df = new DecimalFormat("0.##########");
tvResult.setText(num1 + " " + oper + " " + num2 + " = " + df.format(result));
This will print with up to 10 decimal places.
Many ways to do that, i use:
public static double round(double value, int places) {
if (places < 0)
throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
And then call:
round(yourAnswer, 2)
For BigDecimal:
http://developer.android.com/reference/java/math/BigDecimal.html
Efficient BigDecimal round Up and down to two decimals
Hi all I am having a little trouble handling this question. I have 5 EditText boxes and I ask the user to put a number in them. Then I want to calculate the sum of the EditText boxes and do something with the sum. However I am having trouble in the case if the user don't put a number in all the boxes.
Is it possible to put a default value "0" in the boxes just in case not all the boxes are filled but the sum to be calculated although not all the boxes are filled?
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_extra_question);
textBox1 = (EditText) findViewById(R.id.editText1);
textBox2 = (EditText) findViewById(R.id.editText2);
textBox3 = (EditText) findViewById(R.id.editText3);
textBox4 = (EditText) findViewById(R.id.editText4);
textBox5 = (EditText) findViewById(R.id.editText5);
buttON = (Button) findViewById(R.id.button1);
buttON.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
number1 = Integer.parseInt(textBox1.getText().toString());
number2 = Integer.parseInt(textBox2.getText().toString());
number3 = Integer.parseInt(textBox3.getText().toString());
number4 = Integer.parseInt(textBox4.getText().toString());
number5 = Integer.parseInt(textBox5.getText().toString());
sum = number1 + number2 + number3 + number4 + number5;
if(sum > 100)
{
Toast.makeText(getApplicationContext(), "Nice!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Fail!", Toast.LENGTH_LONG).show();
}
}
});
Do this for each number:
number1 = textBox1.getText().toString().trim().isEmpty()?0:Integer.parseInt(textBox1.getText().trim().toString());
Create on function like this
public int getIntFromString(String str) {
if (str != null) {
if (str.equalsIgnoreCase("")) {
return 0;
} else {
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
return 0;
}
}
} else {
return 0;
}
}
Then Your code should be
number1 = getIntFromString(textBox1.getText().toString().trim());
number2 = getIntFromString(textBox2.getText().toString().trim());
number3 = getIntFromString(textBox3.getText().toString().trim());
number4 = getIntFromString(textBox4.getText().toString().trim());
number5 = getIntFromString(textBox5.getText().toString().trim());
Yes your idea is correct. For each of the edit texts , just check:
if(textBox1.getText().toString().equals(""))
{
number1 = 0;
}
else
number1 = Integer.parseInt(textBox1.getText().toString());
You have to check Empty String using the below code and put "0" in every missing value.
number1 = textBox1.getText().toString().isEmpty()?0:Integer.parseInt(textBox1.getText().toString());
number2 = textBox2.getText().toString().isEmpty()?0:Integer.parseInt(textBox2.getText().toString());
number3 = textBox3.getText().toString().isEmpty()?0:Integer.parseInt(textBox3.getText().toString());
number4 = textBox4.getText().toString().isEmpty()?0:Integer.parseInt(textBox4.getText().toString());
number5 = textBox5.getText().toString().isEmpty()?0:Integer.parseInt(textBox5.getText().toString());