Why my this java interest calculator program not working? - java

I'm very new to android development. I designed and programmed a simple interest calculator. But it works to some extend only and if you try with large number it won't give correct answer and crashes the application. Here is my code
package com.example.minti;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class InterestCalculator extends AppCompatActivity {
float showResultData, totalAmtData;
int firstValueData, secondValueData, thirdValueData;
EditText firstValue, secondValue, thirdValue;
Button findResult;
TextView showResult, totalAmt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_interest_calculator);
firstValue = (EditText) findViewById(R.id.principleAmount);
secondValue = (EditText) findViewById(R.id.tenure);
thirdValue = (EditText) findViewById(R.id.interestRate);
findResult = (Button) findViewById(R.id.intCalculator);
showResult = (TextView) findViewById(R.id.intResult);
totalAmt = (TextView) findViewById(R.id.totalResult);
findResult.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
firstValueData = Integer.parseInt(firstValue.getText().toString());
secondValueData = Integer.parseInt(secondValue.getText().toString());
thirdValueData = Integer.parseInt(thirdValue.getText().toString());
showResultData = (firstValueData*secondValueData*thirdValueData)/36500;
//totalAmtData = showResultData+firstValueData;
showResult.setText(String.valueOf("Interest : " +showResultData));
//totalAmt.setText(String.valueOf("Total Amount : " +totalAmtData));
}
});
}
}
When i try to calculate interest of a long amount. It closes the current activity and sometimes crashes the app. Here is the crash report that i get.
java.lang.NumberFormatException: For input string: "897667979494"
at java.lang.Integer.parseInt(Integer.java:618)
at java.lang.Integer.parseInt(Integer.java:650)
at com.example.minti.InterestCalculator$1.onClick(InterestCalculator.java:41)
at android.view.View.performClick(View.java:7167)
at android.view.View.performClickInternal(View.java:7140)
at android.view.View.access$3500(View.java:813)
at android.view.View$PerformClick.run(View.java:27597)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7509)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995)

The number 897667979494 is too large to fit into an int. Use long or (usually better with money) BigDecimal.

You should change
showResult.setText(String.valueOf("Interest : " +showResultData));
to
showResult.setText("Interest : " + String.valueOf(showResultData));
And can you show the error when your application crashed?

Related

Attempting to create validation for a number, crashes when attempting to test

The Title is the best I could explain it. I am attempting to create a validation for a number box in Java, using android studio. However, the validation, when it should instead display the message "weight must be entered!", the program collapses upon itself. Any idea what could be wrong? Thanks in advance.
package com.example.student.project8a_medicalcalculator;
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.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DecimalFormat;
import java.util.EmptyStackException;
public class MainActivity extends AppCompatActivity {
double weightEntered;
double convertedWeight;
final double conversionRate = 2.2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
final EditText weight = (EditText) findViewById(R.id.Weight);
final RadioButton lbToKilo = (RadioButton) findViewById(R.id.LbToKilo);
final RadioButton kiloToLB = (RadioButton) findViewById(R.id.KiloToLb);
final TextView result = (TextView) findViewById(R.id.Results);
Button convert = (Button) findViewById(R.id.bnConvert);
convert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String weightV;
weightV = weight.getText().toString();
if (weightV.equals(" "))Toast.makeText(MainActivity.this, "Weight must be entered! ", Toast.LENGTH_LONG).show();
weightEntered = Double.parseDouble(weight.getText().toString());
DecimalFormat tenth = new DecimalFormat("#.#");
if (lbToKilo.isChecked()){
if (weightEntered <= 500){
convertedWeight = weightEntered / conversionRate;
result.setText(tenth.format(convertedWeight) + " kilograms");
} else {
Toast.makeText(MainActivity.this, "Pounds must be less than 500", Toast.LENGTH_LONG).show();
}
}
if (kiloToLB.isChecked()){
if (weightEntered <= 225){
convertedWeight = weightEntered * conversionRate;
result.setText(tenth.format(convertedWeight) + " pounds");}
else {
Toast.makeText(MainActivity.this, "Kilos must be less than 225 ", Toast.LENGTH_LONG).show();
}
}
}
});
}
}
Double.parseDouble() will raise NumberFormatException exception and make app crash when when you try to parse an empty string.
you checked the input string, but run Double.parseDouble() even it equals empty.
You could do as below:
if (!weightV.isEmpty()){
weightEntered = Double.parseDouble(weight.getText().toString());
......
}else{
Toast.makeText(MainActivity.this, "Weight must be entered! ", Toast.LENGTH_LONG).show();
......
}
You say: the validation, when it should instead display the message "weight must be entered!", /the program collapses upon itself
So you put a space " " in the EditText and expect to see the Toast.
You would see the Toast if you change the code:
if (weightV.trim().isEmpty()) {
Toast.makeText(MainActivity.this, "Weight must be entered! ", Toast.LENGTH_LONG).show();
return;
}
But without return the code continues to execute and Double.parseDouble(weight.getText().toString()) throws an exception because an empty EditText's text is not a valid number.

Decimal part is lost when displaying the result of division

I'm fairly new to Android Studio. I've tried to create an app that calculates how much you can spend everyday based on you income. My problem is that it doesn't display any decimals. Heres the code:
package com.example.amazi.howmuchmoney;
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;
public class MainActivity extends AppCompatActivity {
EditText et1,et2;
TextView tvResult;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1=(EditText) findViewById(R.id.editText1);
et2=(EditText) findViewById(R.id.editText2);
tvResult=(TextView) findViewById(R.id.textView3);
button=(Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
int num1=Integer.parseInt(et1.getText().toString());
int num2=Integer.parseInt(et2.getText().toString());
int result=num1/num2;
tvResult.setText("Each day you can spend "+result);
}
});
}
}
Mathematical operations performed on integers are exact, therefore;
(int) 3 / (int) 2 = (int) 1
Using double as your data type will fix your problem, although;
Integer.parseInt
Will still return an integer value, try;
Double.parseDouble

find out the log value of a number from input

I have a edittext field for users input. user can enter values up to ten digit number.when clicking on the button, i need to show the log [ mathematics log ] value of that number in double precision.
That i showned below.
If i input xxxxxxxxxx [ consider this as number ]
The output must look like this yy.yy.
package com.example.logvalue;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText edit = (EditText) findViewById(R.id.editText1);
final int noo = Integer.parseInt(edit.getText().toString());
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Toast.makeText(Main.this, String.format("%.2f", Math.log10(noo)) , Toast.LENGTH_LONG).show();
}
});
}
}
Use the String.format("%.2f", Math.log10(number)) syntax.
The String class has this format function exactly for these.
I assume you want logarithm with base of 10.
Explanation: String.format is the Java-equavalient of the traditional printf from C++. The % symbol means there is something to be fetched from the argument list, the point means that we want to specify the number of decimals, and hence we put a 2 after that point.
Hope I helped.

EditText save String as Integer then multiply it by 3 is not working?

I am trying to make a basic conversion tool that i will expand on later. But when i take the information from the EditText and covert it to Integer then try to multiply it, my application crashes on the button click.
My Java code is as follows, New member to this site, but have been using it for help for weeks now, So thanks you have all helped out so much already
package com.example.mayconverter;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Feetyards extends Activity{
EditText feet;
Button convertFeet;
int formula;
TextView displayText;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.feet_yards);
displayText =(TextView) findViewById(R.id.displayText);
formula = 3;
convertFeet = (Button) findViewById(R.id.buttonFeet);
final EditText feet = (EditText) findViewById(R.id.editTextFeet);
convertFeet.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String data = feet.getText().toString();
final int dataint = Integer.parseInt(data);
displayText.setText(dataint + formula);
}
});
}
}
It always helps to post your LogCat errors, but it looks like you have two problems:
You are accidentally creating two variables with the same name feet:
This creates a local feet variable (not what you want)
final EditText feet = (EditText) findViewById(R.id.editTextFeet);
Use this instead to initialize your class variable feet:
feet = (EditText) findViewById(R.id.editTextFeet);
You need to convert your "formula" back into a String:
displayText.setText((dataint + formula) + "");
When you use setText(Int), this tried to load a String value stored in your resources, while setText(String) displays the String passed to the function.
replace this line
displayText.setText(dataint + formula);
with
displayText.setText((dataint + formula)+"");

main method not being called in Android Activity

So i have this code which solves the quadratic equation in java (android development) and it isnt doing anything!!!! The button when i press it does not give the answer at all... i cant even check if it is doing it correctly.
import android.os.Bundle;
import android.app.Activity;
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.support.v4.app.NavUtils;
public class QuadraticEquationSolver extends Activity {
public void main(String[] args){
Button calc = (Button) findViewById(R.id.Calculate);
calc.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
EditText X2 = (EditText)findViewById(R.id.X2);
EditText X = (EditText)findViewById(R.id.X);
EditText Num = (EditText)findViewById(R.id.Num);
TextView ans= (TextView) findViewById(R.id.finalans);
double x2 = Integer.parseInt(X2.getText().toString());
double x = Integer.parseInt(X.getText().toString());
double num = Integer.parseInt(Num.getText().toString());
double finalNum = ((x*-1) + (Math.sqrt((x*x)-(4*x*num))))/(2*x2);
ans.setText("answer: " + finalNum);
}
});
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quadratic_equation_solver);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_quadratic_equation_solver, menu);
return true;
}
First of all, welcome to Android development. I would highly recommend as a starting point you read the App Fundamentals and related guides on the SDK documentation site, as they will help you greatly in your new endeavour.
Android does not use a single entry point (i.e. main method) so your code will not be called. You will want to move all that code into onCreate().
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quadratic_equation_solver);
Button calc = (Button) findViewById(R.id.Calculate);
calc.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
EditText X2 = (EditText)findViewById(R.id.X2);
EditText X = (EditText)findViewById(R.id.X);
EditText Num = (EditText)findViewById(R.id.Num);
TextView ans= (TextView) findViewById(R.id.finalans);
double x2 = Integer.parseInt(X2.getText().toString());
double x = Integer.parseInt(X.getText().toString());
double num = Integer.parseInt(Num.getText().toString());
double finalNum = ((x*-1) + (Math.sqrt((x*x)-(4*x*num))))/(2*x2);
ans.setText("answer: " + finalNum);
}
});
}
I don't do any android programming, but I doubt Android will ever call your main method. The content of this main method must probably be in the onCreate method.
onCreate() is your main() equivalent in Android. Your main() function will never be called. The contents of main() should go in onCreate().

Categories