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

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.

Related

The textbox of the current Activity is not updated when another item is selected in the RadioButton of the previous Activity. Android/Java

The application should count the moments of inertia and moments of resistance of the profiles, and output the value of the selected profile in the TextView.
Application work:
The user enters the value of loads, deflection, length
Selects the required profile via radoiButton
Clicks on the "Execute calculation" button
The application reads and displays the value of the selected profile in the TextView
At the first launch, the application works correctly and everything is displayed. But when you exit to the previous activity to change the profile selection via radoiButton, the value of the text field does not change and remains the same as in the previous selection. Only restarting the entire application helps.
It turns out that to change the cross-section, you need to completely terminate the application each time and re-enter the data.
data input activity1
public void shvellerOnClick(View view) {
radioGroupShveller.removeAllViews();
RadioButton shvellerYRadioButton = new RadioButton(this);
RadioButton shvellerPRadioButton = new RadioButton(this);
shvellerYRadioButton.setText(R.string.shveller_Y);
shvellerPRadioButton.setText(R.string.shveller_P);
radioGroupShveller.addView(shvellerYRadioButton);
radioGroupShveller.addView(shvellerPRadioButton);
shvellerPRadioButton.setOnClickListener(radioButtonClickListener);
shvellerYRadioButton.setOnClickListener(radioButtonClickListener);
shvellerYRadioButton.setId(R.id.idShvellerYRadioButton);
shvellerPRadioButton.setId(R.id.idShvellerPRadioButton);
radioGroupShvellerX2.removeAllViews();
radioGroupDvutavr.removeAllViews();
radioGroupShvellerX2.clearCheck();
radioGroupDvutavr.clearCheck();
}
public void dvaShvelleraOnClick(View view) {
radioGroupShvellerX2.removeAllViews();
RadioButton shvellerYX2RadioButton = new RadioButton(this);
RadioButton shvellerPX2RadioButton = new RadioButton(this);
shvellerYX2RadioButton.setText(R.string.shveller_Y_x2);
shvellerPX2RadioButton.setText(R.string.shveller_P_x2);
radioGroupShvellerX2.addView(shvellerYX2RadioButton);
radioGroupShvellerX2.addView(shvellerPX2RadioButton);
shvellerYX2RadioButton.setOnClickListener(radioButtonClickListener);
shvellerPX2RadioButton.setOnClickListener(radioButtonClickListener);
shvellerYX2RadioButton.setId(R.id.idShvellerYX2RadioButton);
shvellerPX2RadioButton.setId(R.id.idShvellerPX2RadioButton);
radioGroupShveller.removeAllViews();
radioGroupDvutavr.removeAllViews();
radioGroupShvellerX2.clearCheck();
radioGroupDvutavr.clearCheck();
}
View.OnClickListener radioButtonClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioButton rb = (RadioButton)v;
switch (rb.getId()) {
case R.id.idShvellerYRadioButton:
valueSelectedGost = 0;
break;
case R.id.idShvellerPRadioButton:
valueSelectedGost = 1;
break;
case R.id.idShvellerYX2RadioButton:
valueSelectedGost = 10;
break;
case R.id.idShvellerPX2RadioButton:
valueSelectedGost = 11;
break;
case R.id.idDvutavBRadioButton:
valueSelectedGost = 20;
break;
case R.id.idDvutavKRadioButton:
valueSelectedGost = 21;
break;
}
}
};
public void vypolnitRaschetOnClick(View view) {
int putGost = valueSelectedGost;
Intent performCalculationIntent = new Intent(StBalkaSchema1CopyActivity.this, StBalkaShema1RaschetCopyActivity.class);
performCalculationIntent.putExtra("gostInt", putGost);
startActivity(performCalculationIntent);
}
Activity2 calculation
Intent intent = getIntent();
int getGostInt = intent.getIntExtra("gostInt",0);
selectedProfileImageView = (ImageView) findViewById(R.id.selectedProfileImegeView);
selectedProfileTextView = (TextView) findViewById(R.id.selectedProfileTextView);
infoSelectedProfileTextView = (TextView) findViewById(R.id.infoSelectionProfileTextView);
double loadToFormula = Double.parseDouble(loadTextView.getText().toString());
double lengthToFormula = Double.parseDouble(lengthTextView.getText().toString());
double deflectionToFormula = Double.parseDouble(deflectionTextView.getText().toString());
double resultWtr = resultMmax * 100 / (1.12*2.1);
double resultItr = resultMmax * Math.pow(10, 5) * lengthMToFormula * Math.pow(10, 2) * deflectionToFormula / (10 * 2.1 * Math.pow(10, 6));
if (getGostInt >= 0 & getGostInt <= 9){
selectedProfileImageView.setImageResource(R.drawable.shveller);
if (getGostInt == 0){
ShvellerU_GOST_8240_89.addShvellerU();
infoSelectedProfileTextView.setText(ShvellerU_GOST_8240_89.getClosestInertiaResistance(resultItr, resultWtr));
selectedProfileTextView.setText(R.string.shveller_Y);
} else if (getGostInt == 1){
ShvellerP_GOST_8240_89.addShvellerP();
infoSelectedProfileTextView.setText(ShvellerP_GOST_8240_89.getClosestInertiaResistance(resultItr, resultWtr));
selectedProfileTextView.setText(R.string.shveller_P);
}else {
infoSelectedProfileTextView.setText("Профиль не выбран");
selectedProfileTextView.setText("Профиль не выбран");
}
} else if (getGostInt >= 10 & getGostInt <= 19){
selectedProfileImageView.setImageResource(R.drawable.dva_shvellera);
if(getGostInt == 10){
ShvellerUx2_GOST_8240_89.addShvellerUx2();
infoSelectedProfileTextView.setText(ShvellerUx2_GOST_8240_89.getClosestInertiaResistance(resultItr, resultWtr));
selectedProfileTextView.setText(R.string.shveller_Y_x2);
} else if (getGostInt == 11){
ShvellerPx2_GOST_8240_89.addShvellerPx2();
infoSelectedProfileTextView.setText(ShvellerPx2_GOST_8240_89.getClosestInertiaResistance(resultItr, resultWtr));
selectedProfileTextView.setText(R.string.shveller_P_x2);
} else {
infoSelectedProfileTextView.setText("Профиль не выбран");
selectedProfileTextView.setText("Профиль не выбран");
}
}
}
Profile adding method
public class ShvellerU_GOST_8240_89 extends Shveller {
public ShvellerU_GOST_8240_89(String name, double momentSoprotivleniya, double momentInertsii, double massa) {
super(name, momentSoprotivleniya, momentInertsii, massa);
}
public static void addShvellerU() {
ShvellerU_GOST_8240_89 shveller5U = new ShvellerU_GOST_8240_89("5У", 9.1,22.8,4.84);
shveller5U.putIn(shveller5U);
ShvellerU_GOST_8240_89 shveller6_5U = new ShvellerU_GOST_8240_89("6,5У", 15,48.6,5.9);
shveller6_5U.putIn(shveller6_5U);
ShvellerU_GOST_8240_89 shveller8U = new ShvellerU_GOST_8240_89("8У", 22.4,89.4,7.05);
shveller8U.putIn(shveller8U);
ShvellerU_GOST_8240_89 shveller10U = new ShvellerU_GOST_8240_89("10У", 34.8,174.0,8.59);
shveller10U.putIn(shveller10U);
}
}
The error will most likely occur in this block activity2 calculation.
if (getGostInt == 0){
ShvellerU_GOST_8240_89.addShvellerU();
infoSelectedProfileTextView.setText(ShvellerU_GOST_8240_89.getClosestInertiaResistance(resultItr, resultWtr));
selectedProfileTextView.setText(R.string.shveller_Y);
I think that this is due to the fact that when objects are added through the addShvellerU () method, they remain in memory and when a different section is selected, the addDvutavrK () method cannot overwrite another. How to solve this problem?

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 count sum total in Java using Android Studio

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.

How can I generate different random numbers regularly in 4 second?

I'm trying to write a bingo game code. I want to produce 70 random numbers that change every 4 seconds.
I created a countdowntimer and created a random number in 4 seconds by defining a runnable into the finnish section in countdowntimer. But these random numbers may not be different from each other.
Handler handler;
Runnable run;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random random = new Random();
int i = random.nextInt(70);
Random random2 = new Random();
int z = random2.nextInt(70);
int y =random2.nextInt(70);
int x =random2.nextInt(70);
int w =random2.nextInt(70);
int q =random2.nextInt(70);
int v =random2.nextInt(70);
int m =random2.nextInt(70);
int n =random2.nextInt(70);
int l =random2.nextInt(70);
final TextView textView3 = (TextView) findViewById(R.id.textView3);
final TextView textView4 = (TextView) findViewById(R.id.textView4);
final TextView textView5 = (TextView) findViewById(R.id.textView5);
final TextView textView6 = (TextView) findViewById(R.id.textView6);
final TextView textView7 = (TextView) findViewById(R.id.textView7);
final TextView textView8 = (TextView) findViewById(R.id.textView8);
final TextView textView9 = (TextView) findViewById(R.id.textView9);
final TextView textView10 = (TextView) findViewById(R.id.textView10);
final TextView textView2 = (TextView) findViewById(R.id.textView2);
textView2.setText("Lucky number: " + i);
final int a = Integer.parseInt(textView3.getText().toString());
final int b = Integer.parseInt(textView4.getText().toString());
final int c = Integer.parseInt(textView5.getText().toString());
final int d = Integer.parseInt(textView6.getText().toString());
final int e = Integer.parseInt(textView7.getText().toString());
final int f = Integer.parseInt(textView8.getText().toString());
final int g = Integer.parseInt(textView9.getText().toString());
final int h = Integer.parseInt(textView10.getText().toString());
textView9.setText("" + z);
textView10.setText(" "+ y);
textView8.setText(" "+ x);
textView7.setText(" "+ w);
textView6.setText(" "+ q);
textView5.setText(" "+ l);
textView4.setText(" "+ m);
textView3.setText(" "+ n);
CountDownTimer ct0 = new CountDownTimer(60000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("Remaining time: " + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
}
}.start();
CountDownTimer ct1 = new CountDownTimer(4000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
handler = new Handler();
run = new Runnable() {
#Override
public void run() {
int[] numbers = new int[70];
Random random = new Random();
int i = random.nextInt(70);
TextView textView2 = (TextView) findViewById(R.id.textView2);
textView2.setText("Lucky number: " + i);
if ( i == a) {
textView3.setText("ok");
} else if (i == b) {
textView4.setText("ok");
} else if (i == c) {
textView5.setText("ok");
} else if (i == d) {
textView6.setText("ok");
} else if (i == e) {
textView7.setText("ok");
} else if(i == f) {
textView8.setText("ok");
} else if (i == g) {
textView9.setText("ok");
} else if (i == h) {
textView10.setText("ok");
}
handler.postDelayed(this, 4000);
}
};
handler.post(run);
}
}.
start();
}
For 60 seconds, I want to create 70 different numbers every 4 seconds and match these numbers to the other 8 variables. I'd appreciate it if you could help. thanks.
I can give to you a way to do this, to avoid what you are saying :
But these random numbers may not be different from each other.
That's obvious because you do not control it.
I'd say to create a a Set<Integer> of your size that is 70, so you can fill this array doing a simple for loop.
for (int i = 0; i<70; i++) yourSetList.add(i);
Then a good way to "simulate" the bingo is shuffling the list, so you can use
Collections shuffle
Then you can generate a random like this :
Random random = new Random();
int random = random.nextInt(yourSetList.size()) + 1;
Then use random as an index
yourSetList.get(random);
Make sure you remove it from the list to avoid your initial problem
yourSetList.remove(random);

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.

Categories