Can someone tell me, why my app keep getting crashed. Cannot find solution for this and why its happening when TextField is empty
public void contanges(View v){
TextView wynik = (TextView)findViewById(R.id.wynik);
double b = Double.parseDouble(wynik.getText().toString());
if(wynik.getText().length() == 0 ){
wynik.setText("Bad opperand!");
}else if(b % 180 ==0){
wynik.setText("Bad opperand!");
}else {
BigDecimal a = new BigDecimal(wynik.getText().toString());
BigDecimal result = new BigDecimal("0");
result = new BigDecimal(1 / Math.tan(Math.toRadians(a.doubleValue())));
wynik.setText(result.toString());
}
}
Don't check for 0 length. Instead use TextTextUtils.isEmpty(). This way, you can check if the TextView actually has text to parse before you parse it.
TextView wynik = (TextView)findViewById(R.id.wynik);
if (TextUtils.isEmpty(wynik.toString().trim())) {
// Do your stuff here
}
Your error is in this line :
Double.parseDouble(wynik.getText().toString());
You are trying to parse an empty string to double which is not valid.
Add this line before that
if(wynik.getText().length() > 0){
Double.parseDouble(wynik.getText().toString());
}
Also it depends what you are passing as a textview value because if it is not been able to parse than also it will throw an exception
Try passing a double value to edittext when not empty.
Related
I have a simple screen with two EditText Boxes and 1 button. I want users to be able to enter various integers into the boxes and the program will perform different operations based on the specific number entered into the box. I'm trying to have them only enter one number at a time but the code wont seem to execute unless both boxes have something in them. And I'm having the if statements check for nulls on the respective boxes before executing to determine which piece of code to execute.
public void button(View view) {
double x, y;
EditText freq1 = findViewById(R.id.freq1);
EditText freq2 = findViewById(R.id.freq2);
TextView str1 = findViewById(R.id.freqanswer);
TextView str2 = findViewById(R.id.injVolt);
TextView error1 = findViewById(R.id.error1);
String strf1, strf2;
strf1 = freq1.getText().toString();
strf2 = freq2.getText().toString();
try {
f1 = Double.parseDouble(strf1);
f2 = Double.parseDouble(strf2);
if ((f1 >= 225) & (f1 <= 312) & (strf1.isEmpty())) {
x = f1 + 20.6;
y = x / 4;
str1.setText(String.format("%.3f", y));
}
}
catch (Exception e){
error1.setText("splat");
}
finally {
InputMethodManager input = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
input.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
I included only 1 formula for the sake of brevity, but I'm going to be putting about 6 if statements, checking for number ranges and nulls on this button and I just need it to run with one box being empty. I know the formula works by having play with various outputs, it just won't run with the strf1.isEmpty(). Something has to be in that second box for the formula to execute.
Would appreciate any help
I think you should check before assigning:
if(strf1.isEmpty()){strf1="0";} //if assuming zero does not change the formula's output
if(strf2.isEmpty()){strf2="0";}
f1 = Double.parseDouble(strf1);
f2 = Double.parseDouble(strf2);
this way you are assured of a default value.
I'm creating a simple app that calculates BMI and I'm struggling with one small problem. I have 2 edit text fields, which are allowed to type numbers only. The point is when one of the text fields are empty the app is to generate a toast message and display nothing. I wrote an if statement to check if an edit text is empty and if not just to calculate further.
All would work fine, but I needed to put return statement and Android Studio suggested me writing "return 0;" so did I.
This is the code responsible for calculations:
/// parse input value from edittext field into double type
private double weight() {
EditText weightInput = (EditText) findViewById(R.id.weight_input);
String sWeightInput = weightInput.getEditableText().toString();
if (sWeightInput.matches("")){
Toast.makeText(this, R.string.noweight, Toast.LENGTH_SHORT).show();
} else {
String weight = sWeightInput;
double weightTyped = Double.parseDouble(weight);
return weightTyped;
}
return 0;
}
private double heigh() {
EditText heightInput = (EditText) findViewById(R.id.height_input);
String sHightInput = heightInput.getEditableText().toString();
if (sHightInput.matches("")){
Toast.makeText(this, R.string.noheight, Toast.LENGTH_SHORT).show();
} else {
String height = sHightInput;
double heightTyped = Double.parseDouble(height);
heightTyped = heightTyped / 100;
heightTyped = heightTyped * heightTyped;
return heightTyped;
}
return 0;
}
//make calculations and return the output value
public void makeCalculations(View view){
double result = weight() / heigh();
String message = String.valueOf(result);
TextView bmiSummaryTextView = (TextView) findViewById(R.id.bmi_calculation);
bmiSummaryTextView.setText(message);
}
This is the interface of the app.
To sum up, all I want to do is to display nothing instead of NaN (not a number).
Return a non-primitive Double rather than a double, and you will be able to use null as a value. Be sure to check for this value though, or you'll run into a NullPointerException.
Alternatively, you could look into using optionals, but since you're using Android you might need an external library for that (unless your minimum SDK version is high enough, then you can use Java 8's Optional).
The problem is probably if in your calculation weight() / height height is 0 it outputs NaN because it is infinity.
Also put your return 0; after Toast.makeText() in the condition. AS grumbles because you are not returning a value in the if branch.
if (sHightInput.matches("")){
Toast.makeText(this, R.string.noheight, Toast.LENGTH_SHORT).show();
return 0;
}
Maybe this will help you also to avoid dividing by zero.
public void makeCalculations(View view) {
String message = "Invalid input!";
if (weight() > 0 && height() > 0) {
double result = weight() / heigh();
String message = String.valueOf(result);
}
TextView bmiSummaryTextView = (TextView) findViewById(R.id.bmi_calculation);
bmiSummaryTextView.setText(message);
}
I am trying to change the value in a jTextField when I press the UP and DOWN arrow keys on the keyboard. When UP is pressed the value goes up by a set amount and when DOWN is pressed it goes down.
This is what I so far:
private void engineTxtKeyPressed(java.awt.event.KeyEvent evt) {
try{
int code = evt.getKeyCode();
double value = Double.parseDouble(engineTxt.getText());
if (code == KeyEvent.VK_UP) {
value = value + 25.00;
if ((value) > 100.00) {
value = 100.00;
engineTxt.setText(String.format("%.2f", value));
}
}
else if(code == KeyEvent.VK_DOWN){
value = value - 25.00;
if ((value) < 0.00) {
value = 0.00;
engineTxt.setText(String.format("%.2f", value));
}
}
} catch(Exception e){
System.out.println("error");
}
}
Before I put the try/catch in there, the error I got was:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "0,00"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
The list goes all the way down for many lines, basically it would flag anything with parsing and formats throughout the process.
The thing is that I have the same parsing for another 10 TextFields and there is no problem, but this is the only one with a keyEvent. After adding the try/catch I get my sout() message every time i press a key and the rest of the program continues just fine.
When you get to the line :
double value = Double.parseDouble(engineTxt.getText());
The string engineTxt.getText() returns (String) 0,00, which raises an error.
While
double value = Double.parseDouble("0");
System.out.println(value);
Wont raise an exception,
double value = Double.parseDouble("0,00");
System.out.println(value);
does.
Somewhere along the line, there is a , that should'nt be there.
Since this will work:
double value = Double.parseDouble("0.05");
System.out.println(value);
EDIT:
Like someone said in the comments, while the OP is not aware of it, it is a Possible duplicate of parseDouble in Java results to NumberFormatException
I am making a basic calculator for Android in Java. I am stuck in one final step where it must add the input with the previous input. Have a look at the code:
public void displayValue(){
String mything = display.getText().toString();
input = Integer.parseInt(mything);
}
public void number1(View view){
if (input == 0){display.setText("");}
display.append(Integer.toString(1));
displayValue();
}
public void number2(View view){
if (input == 0){display.setText("");}
display.append(Integer.toString(2));
displayValue();
}
public void plus(View view){
displayValue(); //result= 0
result = result + input; //result= input
input = 0; //input=0
//in this step input becomes 0 to let the user enter new number input but this
//input never add the old result and the equal shows the old result.
}
public void equal(View view){
displayValue();
display.setText(Integer.toString(result));
}
I noticed that if I add a line in equal method and add the result to input I get the correct answer but that's not gonna be helpful as there will be minus button too.
Any ideas?
Thanks.
It's definitely hard to tell because you don't include full code, which would be helpful, but could it be because you call displayValue(); in some places before doing the math? Specifically in the plus method.
Ok finally I came up with a solution.
As the only option for calculation of result and new input is in equal method (because logically when user press the equal button, so wants to ends the equation), so I added two boolean values for each minus and plus calculation. Then I added both calculation for adding or minus 2 values.
Then when the user inter first part of the calculation and then hit plus sign, the boolean value of plus becomes true and after entering new input and hitting the equal sign, it does the true part of the calculation. Well it is a bit hard to explain but i guess by looking at the code you would get what I mean.
boolean whenMinus = false;
boolean whenPlus = false;
public void plus(View view){
displayValue();
result = input;
input = 0;
whenPlus = true;
}
public void minus(View view){
displayValue();
result = input;
input = 0;
whenMinus = true;
}
public void equal(View view){
if (whenPlus == true){result = result + input; whenPlus = false;}
if (whenMinus == true){result = result - input; whenMinus = false;}
display.setText(Integer.toString(result));
}
I am not sure if it is the correct way of making this calculator. But I fixed my problem anyway. It would be great to comment me and let me know if it is the standard way or its kinda hacking. I am not a pro anyway.
So, I am messing around with java/android programming and right now I am trying to make a really basic calculator. I am hung up on this issue though. This is the code I have right now for getting the number thats in the textview and making it an int
CharSequence value1 = getText(R.id.textView);
int num1 = Integer.parseInt(value1.toString());
And from what I can tell it is the second line that is causing the error, but im not sure why it is doing that. It is compiling fine, but when it tries to run this part of the program it crashes my app. And the only thing thats in the textview is numbers
Any advice?
I can also provide more of my code if necessary
You can read on the usage of TextView.
How to declare it:
TextView tv;
Initialize it:
tv = (TextView) findViewById(R.id.textView);
or:
tv = new TextView(MyActivity.this);
or, if you are inflating a layout,
tv = (TextView) inflatedView.findViewById(R.id.textView);
To set a string to tv, use tv.setText(some_string) or tv.setText("this_string"). If you need to set an integer value, use tv.setText("" + 5) as setText() is an overloaded method that can handle string and int arguments.
To get a value from tv use tv.getText().
Always check if the parser can handle the possible values that textView.getText().toString() can supply. A NumberFormatException is thrown if you try to parse an empty string(""). Or, if you try to parse ..
String tvValue = tv.getText().toString();
if (!tvValue.equals("") && !tvValue.equals(......)) {
int num1 = Integer.parseInt(tvValue);
}
TextView tv = (TextView)findviewbyID(R.id.textView);
int num = Integer.valueOf(tv.getText().toString());
Here is the kotlin version :
var value = textview.text.toString().toIntOrNull() ?: 0
TextView tv = (TextView)findviewbyID(R.id.textView);
String text = tv.getText().toString();
int n;
if(text.matches("\\d+")) //check if only digits. Could also be text.matches("[0-9]+")
{
n = Integer.parseInt(text);
}
else
{
System.out.println("not a valid number");
}
this code actually works better:
//this code to increment the value in the text view by 1
TextView quantityTextView = (TextView)findViewById(R.id.quantity_text_view);
CharSequence v1=quantityTextView.getText();
int q=Integer.parseInt(v1.toString());
q+=1;
quantityTextView.setText(q +"");
//I hope u like this