Converting a blank input to a zero? - java

I am using eclipse for an android app and the users input a value that is the used in a formula. When they dont enter the value, it will error out so i want any blank inputs to be changed to zeros. heres the code i have:
EditText numAA=(EditText)findViewById(R.id.numAAAn);
Double num1=Double.parseDouble(numAA.getText().toString());
if ((EditText)findViewById(R.id.numAAAn) == null) {
numAA=0;
}
And it has a error on the 0 that says "type mismatch: cannot convert from int to edittext" so im assuming it wants it converted but im not sure how. I tired adding quotes around the 0 but that didnt work either.

Before parsing the double, check if numAA is empty or null. If it is then assign default value.
This is my solution:
Double num1 = 0.0; // Default value..
EditText numAA = (EditText) findViewById(R.id.numAAAn);
if (numAA.getText() != null && numAA.length() != 0) {
num1 = Double.parseDouble(numAA.getText().toString());
} else {
numAA.setText("0");
}
You can create a separate function to perform this operation. Like:
public Double parseInput(Double defaultValue, EditText editText) {
if (editText.getText() != null && editText.length() != 0) {
return Double.parseDouble(editText.getText().toString());
} else {
editText.setText("0");
}
return defaultValue;
}
And from the caller, use it like:
Double num1 = parseInput(0.0, (EditText) findViewById(R.id.numAAAn));

int counter=0;
EditText numAA=(EditText)findViewById(R.id.numAAAn);
Double num1=Double.parseDouble(numAA.getText().toString());
if ((EditText)findViewById(R.id.numAAAn) == null) {
numAA.setText(counter+"");
}
try this:

Try the following code:
EditText numAA=(EditText)findViewById(R.id.numAAAn);
if (numAA.length()==0) {
numAA.setText("0");//or if you want nothing to show in the edittext, leave this one blank
} else {
Double num1=Double.parseDouble(numAA.getText().toString());
}
}
The length() method checks the length of the string within an edittext.

Related

How Delete Last number of a float in android (java)

I am building a calculator app and everything is working properly but I don't know the code for backspace.
public class MainActivity extends AppCompatActivity {
// UI Elements
private TextView num_input;
private TextView num_input;
private ImageButton num_backspace;
private float input, input2 ;
boolean Addition, Subtract, Multiplication, Division, mRemainder, decimal, add_sub;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing
num_input = findViewById(R.id.num_input);
num_output = findViewById(R.id.num_output);
num_backspace = findViewById(R.id.num_backspace);
num_backspace.setOnClickListener(new View.OnClickListener() {
#Override
//TODO: the backslash code goes here.
});
}
}
I tried doing this👇🏻
num_backspace.setOnClickListener(new View.OnClickListener() {
#Override
input = Float.parseFloat(num_input.getText() + "");
String sample_input = Float.toString(input);
sample_input = sample_input.substring(0,sample_input.length() - 1);
});
Some help would be great!
thanks in advance
It's better to store input as a String, not float. Because before you start doing mathematical calculations it's just a String input, and "backspace" means basically removing one character, it's not a mathematical operation. So, provided input is a String, backspace code will be:
input = input(0, input.length() - 1);
num_input.setText(input);
And before doing calculations convert your String input into float via
float operand = Float.parseFloat(input);
Put this code inside your setOnClickListener
String value = num_input.getText().toString();
if (value != null && value.length() > 0 ) {
value = value.substring(0, value.length() - 1);
}
num_input.setText(value);
How this is usually done is getting the current value (entered number) in the TextView, remove the last character from the string and writing it back to the TextView.

How to make calculator over two activities

I have made an app where the user selects a food type, enters a weight and then the app calculates the calories. This calorie is then moved onto the MainActivity (when the 'Save' button is pressed) where the total calories will be displayed for that day.
I need the app to take all calories calculated and add them onto any existing values on the main activity. I wrote the code below, however the app crashes when I press the save button my second activity.
String greeting = getIntent().getStringExtra("Greeting Message");
EditText editText1 = (EditText)findViewById(R.id.editText1);
String value = editText1.getText().toString();
Integer aValue = (value != null && !value.isEmpty()) ? Integer.parseInt(value) : 0 ;
Integer bValue = (greeting != null && !greeting.isEmpty()) ? count +=Integer.parseInt(greeting) : 0 ;
editText1.setText(count + "");
Stack Error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nicola.student.mealtracker/com.nicola.student.mealtracker.MainActivity}: java.lang.NumberFormatException: Invalid int: "70.0Cal"
You should check Your value String, Your exception tells me that the String is "70.0Cal". First, You can get a substring, if You know that the last three signs are allways "Cal"
String value = value.substring(0,substring.length()-3);
and second, You have a decimal value, so You should use not integer, You should use Float or double.
also, You should check if the text in the EditText is not null or empty:
String edittextText = editText1.getText().toString();
if(edittextText!=null && !edittextText.equals("")){
//start calculating
}
Either value, or greeting has a value that cannot be converted to int : "70.0Cal".
So remove the suffic "Cal" , and if you have to deal with fractions, use double instead of int.
Looking at the short stack trace provided I can see that you are parsing a String value that is not in a correct Integer format.
You will have to do some validation on the field to make sure that the input provided is a valid numeric value. You can do that by using the following method or by setting the EditText inputType android:inputType="number"
/**
* Checks if the text is a valid numeric value
* #param value
* #return valid
*/
public static boolean isNumeric(String value) {
if (!isNull(value)) {
if (value.matches("[-+]?\\d*\\.?\\d+")) {
return true;
}
}
return false;
}
I would suggest not appending Cal to the value returned. Keep the input numeric. Rather add the "Cal" value in a TextView next to your EditText.
Implement it this way by using the isNumeric method to check the value before parsing.
public void executeYourCode() {
//Parse your values to Double
//as you are using Double values
Double aValue = getCheckedValue(value) ;
Double bValue = getCheckedValue(greeting);
count+= bValue;
editText1.setText(String.valueOf(count));
}
public int getCheckedValue(String value) {
if (value != null && !value.isEmpty() && isNumeric(value)) {
return Double.parseDouble(value.trim());
}
return 0;
}

EditText text cannot be converted to int as there is no text there

Basically I need to check that the user input from inputET (an EditText) is equal to the integer, correctAnswer. The problem I'm getting is that "" (which is the text in the EditText field) cannot be converted to an int. Is there any other ways of achieving this or catching the error, I've tried the following code which to my understanding asks if the string in the EditText is not equal to "". Am i going the right way about this or is there an easier way?
// check the input
if (inputET.getText().toString() != "") {
if (correctAnswer == Integer.parseInt(inputET.getText()
.toString())) {
inputET.setText("");
newSum();
}
}
if the user inputs the same int as the correctAnswer integer then the EditText text is reset to "".
Thanks for any help.
try this:
if (!inputET.getText().toString().equals("")) {
if (correctAnswer == Integer.parseInt(inputET.getText()
.toString())) {
inputET.setText("");
newSum();
}
}
Used .equals() method for String comparison.
Based on your requirement I think using TextUtil class will be right way to go for checking the edittext is empty or not.
if(!TextUtils.isEmpty( inputET.getText().toString())){
if (correctAnswer == Integer.parseInt(inputET.getText()
.toString())) {
inputET.setText("");
newSum();
}
}
rather tha doing if (inputET.getText().toString() != "") have a try with
if (!inputET.getText().toString().equals(""))
print the "inputET.getText().toString()" to console and see what it returns. I would hope you need to check the following
String str = inputET.getText().toString()
if (null!=str && str.trim().equals("")) {
if(inputET.getText().toString()!=null&&!(inputET.getText().toString().isEmpty())){
//code for mot null
}else{
//code for null
}

Display message dialog if JTextField does not contain data

I am writing a BMI calculator application. Currently an error happens which causes the program to stop working if I do not enter data into one field. For instance, there are two JTextFIelds for 'height', one being feet and the other inches. If I just input '6' into the feet JTextField and enter nothing into inches JTextField, then enter my weight in the weight JTextField and click on calculate, it does not work.
What I want to do is display a message dialog saying "Please make sure all fields are filled in" if one field does not contain data.
Below is the ActionHandler code that is added to my 'Calculate' button.
public void actionPerformed(ActionEvent e) {
double heightFT = ((Double.parseDouble(heightFt_TF.getText()));
double heightIn = (Double.parseDouble(heightIn_TF.getText()));
double weight = (Double.parseDouble(weight_TF.getText()));
double totalHeight = (heightFT*12) + heightIn;
BMI = (weight / (totalHeight*totalHeight)) * 703;
String s = BMI+"";
s = s.substring(0,4);
BMI_TF.setText(s);
}
Solved
I have now fixed the problem. What I did was add 'throws NumberFormatException' in the method and did a try catch. In the try code block I wrote the code I want to execute if all data fields are entered. In the catch clause I wrote code that uses the NumberFormatException and simply displays the message dialog with the error message. Now, if one field is not entered, the message dialog appears!
Just check if your JTextField objects contain text.
E.g:
if (heightFt_TF.getText() == null || heightIn_TF.getText() == null || weight_TF.getText() == null) {
JOptionPane.showMessageDialog(null, "Please make sure all fields are filled in");
}
Of course you also have to make sure, that the content of the textfields really contains a number.
Download Apache Commons Lang library and use StringUtils.isBlank(myTextField.getText()); to validate your fields.
public boolean validateFields() {
if (StringUtils.isBlank(heightFt_TF.getText()) {
// show message
return false;
}
if (StringUtils.isBlank(weight_TF.getText()) {
// show message
return false;
}
return true;
}
Only run your calculation if validateFields() returns true.
public boolean validate(JTextField field) {
boolean result = field.getText() != null;
if (result) {
try {
Double.parseDouble(field.getText()));
} catch(NumberFormatException e) {
result = false
}
}
return result;
}

How to check an empty Double JTextField

I've been working this for 2 days but I can't still figure how to check if the jtextfield is empty (Double not String) before passing it to my database.
I figured it out how to validate String if the field is empty, but I need to put the right code on how to validate Double if the field is empty.
Thanks in advance.
Here's my code:
private void saveButton3ActionPerformed(java.awt.event.ActionEvent evt) {
String inventcodef = inventCodeField.getText();
String inventnamef = inventNameField.getText();
String categ = cmbname.getSelectedItem().toString();
double inventreorderf = Double.parseDouble(inventReorderField.getText());
..............
if ((inventCodeField.trim().Length()==0) || (inventNameField.trim().Length()==0)
To enforce formatting (numeric etc) you can use JFormattedTextField.
To ensure values are not blank see No blanks in JTextField
You are reading the double at first as a String. So, you can do something like this:
double inventreorderf;
if (inventReorderField.getText().trim().length == 0)
{
//Do something which should happen when the field is empty
}
else
{
try
{
inventreorderf = Double.parseDouble(inventReorderField.getText());
}
catch (Exception e)
{
//The user has entered an invalid number. Notify him/her here.
}
}

Categories

Resources