How to count sum total in Java using Android Studio - java

I just learned Java using Android Studio.
My code error for use integer to count sum.
I try to decode string to integer but still error.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtvalue = (EditText) findViewById(R.id.value);
final Spinner edtjw = (Spinner) findViewById(R.id.spinner1);
txtpa = (TextView) findViewById(R.id.pa);
txttotal = (TextView) findViewById(R.id.total);
btncount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String value = edtvalue.getText().toString().trim();
String jw = edtjw.getSelectedItem().toString().trim();
double h = Double.parseDouble(value);
double j = Double.parseDouble(jw);
String numbertostring = String.format ("%.2f", (0.02*h));
String numbertostring2 = String.format ("%.2f", (0.025*h));
String numbertostring3 = String.format ("%.2f", (0.0275*h));
if (j == 1){
txtpa.setText(numbertostring);
} else if (j ==2){
txtpa.setText(numbertostring);
} else if (j ==3){
txtpa.setText(numbertostring);
} else if (j ==4){
txtpa.setText(numbertostring2);
} else if (j ==5){
txtpa.setText(numbertostring3);
} else {
txtpa.setText(0);
}
int tot = (h*j)+txtpa;
txttotal.setText("Total : " + tot);
}}

By looking at the code snippet, you should get string value from txtpa which is of type TextView, then parse it into double
double tot = (h*j)+Double.parseDouble(txtpa.getText().toString());
as mentioned in the above comment by Naitik Soni.

Related

How to randomly generate random operators in android studio

public class MainActivity extends AppCompatActivity {
Button startButton;
ArrayList<Integer> answers=new ArrayList<Integer>();
int LocationOfRightAnswer;
TextView resultTextView;
TextView pointText;
Button button1;
Button button2;
Button button3;
Button button4;
int score=0;
int numberofquestions = 0;
TextView sumText;
TextView timertext;
RelativeLayout game;
Button playAgain;
public void playAgain(View view) {
score = 0;
numberofquestions = 0 ;
timertext.setText("30s");
pointText.setText("0/0");
resultTextView.setText("");
playAgain.setVisibility(View.INVISIBLE);
generateQuestion();
new CountDownTimer(30100,1000) {
#Override
public void onTick(long millisUntilFinished) {
timertext.setText(String.valueOf(millisUntilFinished / 1000) + "s");
}
#Override
public void onFinish() {
playAgain.setVisibility(View.VISIBLE);
timertext.setText("0s");
resultTextView.setText("Your Score is " + Integer.toString(score) + "/" + Integer.toString(numberofquestions));
}
}.start();
}
public void generateQuestion() {
Random random = new Random();
int a = random.nextInt(21);
int b = random.nextInt(21);
char[] ops = {'+' , '-' ,'*', '/'};
int l = random.nextInt(3) ;
sumText.setText(Integer.toString(a) + "+" + Integer.toString(b) );
LocationOfRightAnswer = random.nextInt(4);
answers.clear();
int incorrectAnswer;
for (int i=0; i<4; i++) {
if (i == LocationOfRightAnswer) {
answers.add(a + b);
}else {
incorrectAnswer = random.nextInt(41);
while (incorrectAnswer == a + b) {
incorrectAnswer = random.nextInt(41);
}
answers.add(incorrectAnswer);
}
}
button1.setText(Integer.toString(answers.get(0)));
button2.setText(Integer.toString(answers.get(1)));
button3.setText(Integer.toString(answers.get(2)));
button4.setText(Integer.toString(answers.get(3)));
}
public void chooseAnswer(View view) {
if (view.getTag().toString().equals(Integer.toString(LocationOfRightAnswer))) {
score++;
resultTextView.setText("Correct");
} else {
resultTextView.setText("Wrong!");
}
numberofquestions++;
pointText.setText(Integer.toString(score) + "/" + Integer.toString(numberofquestions));
generateQuestion();
}
public void start (View view) {
startButton.setVisibility(View.INVISIBLE);
game.setVisibility(View.VISIBLE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton =(Button) findViewById(R.id.startButton);
sumText = (TextView) findViewById(R.id.sumTextView);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
resultTextView = (TextView) findViewById(R.id.resultTextView);
pointText = (TextView) findViewById(R.id.pointsTextView);
timertext = (TextView) findViewById(R.id.timerTextView);
playAgain = (Button) findViewById(R.id.playAgain);
game = (RelativeLayout) findViewById(R.id.gamelayout) ;
playAgain(findViewById(R.id.playAgain));
}
}
please help me to adjust my code so that I the app can use all operators instead of just addition. I have tried to do it but I have only managed to create the array list for the operators but I could not find a way to change the code to include all of the operators.
Try this:
ArrayList<Double> answers=new ArrayList<Double>();
public void generateQuestion() {
Random random = new Random();
int a = random.nextInt(21);
int b = random.nextInt(21);
char[] ops = {'+' , '-' ,'*', '/'};
int l = random.nextInt(3) ;
char op = ops[random.nextInt(4)];
double correctAns=0;
switch(op){
case '+' : correctAns = a+b;
break;
case '/' : correctAns = (double)a/b;
break;
case '*' : correctAns = a*b;
break;
case '-' : correctAns = a-b;
break;
}
sumText.setText(Integer.toString(a) + op + Integer.toString(b) );
LocationOfRightAnswer = random.nextInt(4);
answers.clear();
int incorrectAnswer;
for (int i=0; i<4; i++) {
if (i == LocationOfRightAnswer) {
answers.add(correctAns);
}else {
incorrectAnswer = random.nextInt(41);
while (incorrectAnswer != correctAns) {
incorrectAnswer = random.nextInt(41);
}
answers.add((double)incorrectAnswer);
}
}
button1.setText(Double.toString(answers.get(0)));
button2.setText(Double.toString(answers.get(1)));
button3.setText(Double.toString(answers.get(2)));
button4.setText(Double.toString(answers.get(3)));
}
change ArrayList<Integer> answers=new ArrayList<Integer>(); to ArrayList<Double> answers=new ArrayList<Double>(); (int/int can be a double)
create a double variable contains the right answer (int/int can be a double)
choose an operation randomly.
use switch to define what operation is needed on a and bin case that every operation selected.
set the text to Integer.toString(a) + op + Integer.toString(b) instead of Integer.toString(a) + "+" + Integer.toString(b)
swap a+b to correctAns

How to make Toast pop up if EditText field is empty or the inputted value is equal to 0?

First of all, I'm new to Android Studio. I'm currently trying to make a BMI calculator app where the user has to enter their weight and height and select the unit of measurement used for both. A Toast message (R.string.toastError) should pop up upon clicking a button if: (1-2) the EditText fields for weight and height are empty and (3) if the value of HeightInput is less than or equal to zero; else, the calculation should proceed.
The whole math part worked fine when I tested it, but when I left the fields blank, the app just crashes. The Toast pops up though when HeightInput = 0, but not when the EditText field for Weight is left empty at the same time. I think it's the way I wrote the 'if' statement that's giving me a problem.
// if edit text is empty
if (editTextWeightInput.getText().toString().length() == 0 || editTextHeightInput.getText().toString().length() == 0 || HeightInput <= 0) {
Toast.makeText(getApplicationContext(), R.string.toastError, Toast.LENGTH_SHORT).show();
} else {
double finalheight = Math.pow((HeightInput * constantHeight), 2.00);
double BodyMassIndex = (WeightInput * constantWeight) / finalheight;
DecimalFormat BodyMassIndexFormat = new DecimalFormat("##.##");
TextView textViewResult = (TextView) findViewById(R.id.textViewBmiResult);
textViewResult.setText(BodyMassIndexFormat.format(BodyMassIndex));
}
Here's the whole code for reference:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// weight units spinner
final Spinner spinWeightUnit = (Spinner) findViewById(R.id.spinnerWeightUnit);
spinWeightUnit.setOnItemSelectedListener(this);
ArrayAdapter <CharSequence> WeightList = ArrayAdapter.createFromResource(this, R.array.WeightUnits, android.R.layout.simple_spinner_item);
WeightList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinWeightUnit.setAdapter(WeightList);
// height units spinner
final Spinner spinHeightUnit = (Spinner) findViewById(R.id.spinnerHeightUnit);
spinHeightUnit.setOnItemSelectedListener(this);
ArrayAdapter <CharSequence> HeightList = ArrayAdapter.createFromResource(this, R.array.HeightUnits, android.R.layout.simple_spinner_item);
HeightList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinHeightUnit.setAdapter(HeightList);
// calculate button
Button buttonCalculate = (Button) findViewById(R.id.buttonCalculate);
buttonCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// declaration
EditText editTextWeightInput = (EditText) findViewById(R.id.editTextWeightInput);
EditText editTextHeightInput = (EditText) findViewById(R.id.editTextHeightInput);
double WeightInput = Double.valueOf(editTextWeightInput.getText().toString());
double HeightInput = Double.valueOf(editTextHeightInput.getText().toString());
String finalWeightUnit = String.valueOf(spinWeightUnit.getSelectedItem());
String finalHeightUnit = String.valueOf(spinHeightUnit.getSelectedItem());
double constantWeight;
double constantHeight;
// weight conversion constant
if (finalWeightUnit.equals("kilograms")) {
constantWeight = 1.00;
} else {
constantWeight = 1 / 2.204623;
}
// height conversion constant
switch (finalHeightUnit) {
case "inches":
constantHeight = 0.0254;
break;
case "centimeters":
constantHeight = 0.01;
break;
case "feet":
constantHeight = 1 / 3.2808;
break;
default:
constantHeight = 1.00;
break;
}
// if edit text is empty
if (editTextWeightInput.getText().toString().length() == 0 || editTextHeightInput.getText().toString().length() == 0 || HeightInput <= 0) {
Toast.makeText(getApplicationContext(), R.string.toastError, Toast.LENGTH_SHORT).show();
} else {
double finalheight = Math.pow((HeightInput * constantHeight), 2.00);
double BodyMassIndex = (WeightInput * constantWeight) / finalheight;
DecimalFormat BodyMassIndexFormat = new DecimalFormat("##.##");
TextView textViewResult = (TextView) findViewById(R.id.textViewBmiResult);
textViewResult.setText(BodyMassIndexFormat.format(BodyMassIndex));
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
I'd appreciate any help! Thanks!
Try below in if statement
if (editTextWeightInput.getText().toString().trim().isEmpty() || editTextHeightInput.getText().toString().trim().isEmpty() || HeightInput <= 0)
When you leave an EditText Empty the getString() function returns a null value. First you need to check for null in the if condition.
if (editTextWeightInput.getText() == null || editTextWeightInput.getText().toString().length() == 0 || HeightInput <= 0)
You need to validate your declaration code also.
// declaration
EditText editTextWeightInput = (EditText) findViewById(R.id.editTextWeightInput);
EditText editTextHeightInput = (EditText) findViewById(R.id.editTextHeightInput);
if(TextUtil.isEmpty(editTextWeightInput.getText().toString())||TextUtil.isEmpty(editTextHeightInput.getText().toString())){
Toast.makeText(getApplicationContext(), R.string.toastError,
Toast.LENGTH_SHORT).show();
}else{
double WeightInput = Double.valueOf(editTextWeightInput.getText().toString());
double HeightInput = Double.valueOf(editTextHeightInput.getText().toString());
String finalWeightUnit = String.valueOf(spinWeightUnit.getSelectedItem());
String finalHeightUnit = String.valueOf(spinHeightUnit.getSelectedItem());
double constantWeight;
double constantHeight;
}

How to make my variable = the item from the Drop Down Menu

I have a Spinner that has 16 values. 24, 24 1/16, 24 2/16 .... 25. I want to take the one the selected and put it into a variable "w" in the form of a double(decimal). I want to use that variable in the calculations below. I've only made three if Statements for simplicity, but just know there will be 16 of them if it affects it somehow. But in the Calculations they show up as not defined.
public void calculate(View view) {
EditText length_find = findViewById(R.id.feet);
EditText pounds_find = findViewById(R.id.pounds);
DecimalFormat df = new DecimalFormat("###.###");
Spinner width_select = findViewById(R.id.width_select);
ArrayAdapter<String> myAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.width));
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
width_select.setAdapter(myAdapter);
width_select.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object item = parent.getItemAtPosition(position);
if (position == 0){
double w = 24;
}
if (position == 1){
double w = 24.0625;
}
if (position == 2){
double w = 24.125;
}
}
});
try {
double d = .29;
double h = .002;
//This Calculates if Pounds are given
if (length_find.getText().toString().equals("")){
Toast.makeText(MainActivity.this, "Given Pounds", LENGTH_LONG).show();
double pounds = Double.parseDouble(pounds_find.getText().toString());
//THIS IS THE MATH PORTION
double length_d = (pounds / (w * h * d * 12));
String length = Double.toString(Double.parseDouble(df.format(length_d)));
final TextView zTextView = (TextView) findViewById(R.id.length_show);
zTextView.setText("Feet: " + length);
final TextView mTextView = (TextView) findViewById(R.id.pound_show);
mTextView.setText("Pounds: ");
length_find.getText().clear();
pounds_find.getText().clear();
}
//This Calculates if Length is given
if (pounds_find.getText().toString().equals("")){
Toast.makeText(MainActivity.this, "Given Length", LENGTH_LONG).show();
Double length = Double.parseDouble(length_find.getText().toString());
//THIS IS THE MATH PORTION
double answer_pounds_d = (w * h * length * 12 * d);
String answer_pounds = Double.toString(Double.parseDouble(df.format(answer_pounds_d)));
final TextView mTextView = (TextView) findViewById(R.id.pound_show);
mTextView.setText("Pounds: " + answer_pounds);
final TextView zTextView = (TextView) findViewById(R.id.length_show);
zTextView.setText("Feet: ");
length_find.getText().clear();
pounds_find.getText().clear();
}
if((pounds_find).getText().toString().trim().length() > 0 && (length_find).getText().toString().trim().length() > 0){
Toast.makeText(MainActivity.this, "Whata hell you need me for mate!", LENGTH_LONG).show();
}
}
catch(Exception ex) {
//Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
}
}
Since you're only creating the variable in the if statements inside onItemClick, they're only accessible inside those if statements. My suggestion would probably be to create it right before the if statements and then assign it a value in the statements. And in order to use it you'll probably have to move all the math and stuff to inside onItemClick.
Edit: untested, but my guess would be something like this:
public void calculate(View view) {
EditText length_find = findViewById(R.id.feet);
EditText pounds_find = findViewById(R.id.pounds);
DecimalFormat df = new DecimalFormat("###.###");
Spinner width_select = findViewById(R.id.width_select);
ArrayAdapter<String> myAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.width));
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
width_select.setAdapter(myAdapter);
width_select.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object item = parent.getItemAtPosition(position);
double w = 0;
if (position == 0){
double w = 24;
}
if (position == 1){
double w = 24.0625;
}
if (position == 2){
double w = 24.125;
}
try {
double d = .29;
double h = .002;
//This Calculates if Pounds are given
if (length_find.getText().toString().equals("")){
Toast.makeText(MainActivity.this, "Given Pounds", LENGTH_LONG).show();
double pounds = Double.parseDouble(pounds_find.getText().toString());
//THIS IS THE MATH PORTION
double length_d = (pounds / (w * h * d * 12));
String length = Double.toString(Double.parseDouble(df.format(length_d)));
final TextView zTextView = (TextView) findViewById(R.id.length_show);
zTextView.setText("Feet: " + length);
final TextView mTextView = (TextView) findViewById(R.id.pound_show);
mTextView.setText("Pounds: ");
length_find.getText().clear();
pounds_find.getText().clear();
}
//This Calculates if Length is given
if (pounds_find.getText().toString().equals("")){
Toast.makeText(MainActivity.this, "Given Length", LENGTH_LONG).show();
Double length = Double.parseDouble(length_find.getText().toString());
//THIS IS THE MATH PORTION
double answer_pounds_d = (w * h * length * 12 * d);
String answer_pounds = Double.toString(Double.parseDouble(df.format(answer_pounds_d)));
final TextView mTextView = (TextView) findViewById(R.id.pound_show);
mTextView.setText("Pounds: " + answer_pounds);
final TextView zTextView = (TextView) findViewById(R.id.length_show);
zTextView.setText("Feet: ");
length_find.getText().clear();
pounds_find.getText().clear();
}
if((pounds_find).getText().toString().trim().length() > 0 && (length_find).getText().toString().trim().length() > 0){
Toast.makeText(MainActivity.this, "Whata hell you need me for mate!", LENGTH_LONG).show();
}
}
catch(Exception ex) {
//Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
}
}
}
});
Just make your variable 'w' a global variable for the activity.As your variable 'w' is local to the scope of 'if statements' and is undefined outside it.

Android empty editText is crashing my program [duplicate]

This question already has answers here:
How to parse a double from EditText to TextView? (Android)
(9 answers)
Closed 6 years ago.
First time into Java and I'm trying to create a simple tips calculator for my coworkers at the restaurant I work for, but when I leave one of the editText fields empty the program crashes.
MainACtivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
totalTipsInput = (EditText) findViewById(R.id.totalTipsInput);
waiter1Hours = (EditText) findViewById(R.id.waiter1Hours);
waiter2Hours = (EditText) findViewById(R.id.waiter2Hours);
waiter3Hours = (EditText) findViewById(R.id.waiter3Hours);
waiter4Hours = (EditText) findViewById(R.id.waiter4Hours);
tipsPerHourView = (TextView) findViewById(R.id.tipsPerHourView);
totalHoursView = (TextView) findViewById(R.id.totalHoursView);
barsCutView = (TextView) findViewById(R.id.barsCutView);
waiter1Pay = (TextView) findViewById(R.id.waiter1Pay);
waiter2Pay = (TextView) findViewById(R.id.waiter2Pay);
waiter3Pay = (TextView) findViewById(R.id.waiter3Pay);
waiter4Pay = (TextView) findViewById(R.id.waiter4Pay);
taxDepositView = (TextView) findViewById(R.id.taxDepositView);
Button calcBtn = (Button) findViewById(R.id.calcBtn);
calcBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
double totalTips = Double.parseDouble(totalTipsInput.getText().toString());
double cWaiter1Hours = Double.parseDouble(waiter1Hours.getText().toString());
double cWaiter2Hours = Double.parseDouble(waiter2Hours.getText().toString());
double cWaiter3Hours = Double.parseDouble(waiter3Hours.getText().toString());
double cWaiter4Hours = Double.parseDouble(waiter4Hours.getText().toString());
double resultTotalHours = cWaiter1Hours + cWaiter2Hours + cWaiter3Hours + cWaiter4Hours;
double resultBarsCut = (totalTips * 7) / 100;
double resultTaxDeposit = resultTotalHours * 3;
double resultTipsPerHour = (totalTips - resultBarsCut - resultTaxDeposit) / resultTotalHours;
double resultWaiter1Pay = cWaiter1Hours * resultTipsPerHour;
double resultWaiter2Pay = cWaiter2Hours * resultTipsPerHour;
double resultWaiter3Pay = cWaiter3Hours * resultTipsPerHour;
double resultWaiter4Pay = cWaiter4Hours * resultTipsPerHour;
totalHoursView.setText(Double.toString(resultTotalHours));
tipsPerHourView.setText(Double.toString(resultTipsPerHour));
barsCutView.setText(Double.toString(resultBarsCut));
waiter1Pay.setText(Double.toString(resultWaiter1Pay));
waiter2Pay.setText(Double.toString(resultWaiter2Pay));
waiter3Pay.setText(Double.toString(resultWaiter3Pay));
waiter4Pay.setText(Double.toString(resultWaiter4Pay));
taxDepositView.setText(Double.toString(resultTaxDeposit));
}
});
}
Tried to do something like this but got an error with .length():
if (double totalTips = Double.parseDouble(totalTipsInput.getText().toString()).length() < 1 || totalTipsInput = null) {
totalTips = 0
} else {
double totalTips = Double.parseDouble(totalTipsInput.getText().toString());
}
Use this method in your class:
public static Double returnDouble(EditText editText)
{
try {
if(editText.getText().toString().isEmpty())
{
return 0d;
}
else
{
return Double.parseDouble(editText.getText().toString());
}
} catch (NumberFormatException e) {
return 0d;
}
}
You can do something like this to make sure that the input to the "parseDouble" is valid:
double totalTips = 0;
Editable totalString = totalTipsInput.getText();
if(totalString.length() > 0){
totalTips = Double.parseDouble(totalString.toString());
}
If the "totalTips" field can take user input you need to make sure they can only enter a valid number. The lazy way might be to put a try/catch around the parseDouble as well, and handle the case where someone may enter something that can't be parsed to a double (ie, empty string, letters, malformed numerical value)
I would recommend not trusting users to always input valid values in the rest of the waiter hours fields as well. You would want to do similar checks on those fields before attempting to parse the input.

Not able to display very large calculation value in editext

private TextView info;
private EditText input;
private Button getInfo;
long answer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getInfo = (Button) findViewById(R.id.button1);
getInfo.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
input = (EditText) findViewById(R.id.editText1);
String s2 = input.getText().toString();
long inputNumber = Integer.parseInt(s2);
for (int i = 0; i <= inputNumber; i++) {
answer = fibonacci(i);
}
input.setText(answer + "");
}
});
}
public static long fibonacci(long n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
I made a program which generates fibonacci series for the number I give input through edit text and display the output value in edittext .Issue is when I enter 30 it generates fibonacci series but when I enter 50 or 100 app does not respond and stops .
I think it is because you have a lot of calculation on UI thread.
Try calculate it in AssyncTask, for example.

Categories