Android: switch case & random number code in the case - java

Android, java, studio 4.0.1
Trying to code by my own, I am facing an issue which I do not understand from the compiler statements.
Basically, when you click a radio button, a random number is generated in the textview field.
My problem is that the random code written in the case of the clicked radio button is not accepted by the compiler.
Here is the code:
package com.example.random;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
TextView MytextView = (TextView)findViewById(R.id.MytextView);
int random;
int random2;
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radioButton01:
if (checked)
// 0 or 1 code
random = getRandomNumber(0,1);
MytextView.setText(random.toString());
break;
case R.id.radioButton1to6:
if (checked)
// 1 to 6 code
random2 = getRandomNumber(1,6);
MytextView.setText(random2.toString());
break;
}
}
private int getRandomNumber(int min,int max) {
return (new Random()).nextInt((max - min) + 1) + min;
}
}
I presume that the 2 lines 'Int random;' are wrong, but the compiler seems to want to have them here.
I would have understood that the line 'random = getRandomNumber(0,1);' would have be sufficient in the case part of the code, but the compiler marks 'random' in red.
So far, the compiler says: 'error: int cannot be dereferenced in the MytextView.setText(random.toString());' of the //0 or 1 code part.
I would like to understand what I am missing here. Thanks in advance.
(Or asked simpler: how does one code a random function in a switch/case ?)

ok I found the solution. A possible working code is:
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
TextView MytextView = (TextView)findViewById(R.id.MytextView);
final Random rnd = new Random();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radioButton01:
if (checked)
// 0 or 1 code
MytextView.setText(String.valueOf(rnd.nextInt(3-0) + 0));
break;
case R.id.radioButton1to6:
if (checked)
// Dice 1 to 6 code
MytextView.setText("1 to 6");
break;
case R.id.radioButton1to10:
if (checked)
// 1 to 10 code
MytextView.setText("1 to 10");
break;
}
}
And the 'private int getRandomNumber' at the end can be deleted. No need of it.

Related

I want visible button has removed it text from TextView

I want visible button has removed it text from TextView
i am making keyboard typing in text view I have 4 buttons b1,b2,b3,backspace.
when I clicking on b1 typing in textview "A" and b1 invisible
then when I clicking backspace button its remove last char but does not appear last button has clicked
my project
https://youtu.be/_pLEUevM8aA
java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//my buttons
Button b1,b2,b3,backspace;
//my text view
TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView)findViewById(R.id.txt);
b1 = (Button)findViewById(R.id.b1);
b2 = (Button)findViewById(R.id.b2);
b3 = (Button)findViewById(R.id.b3);
backspace = (Button)findViewById(R.id.backspace);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
backspace.setOnClickListener(this);
}
//on clike listener
#Override
public void onClick(View view) {
switch (view.getId()){
//b1 on click
case R.id.b1:
txt.setText(txt.getText().toString() + b1.getText());
b1.setVisibility(View.INVISIBLE);
break;
//b2 on click
case R.id.b2:
txt.setText(txt.getText().toString() + b2.getText());
b2.setVisibility(View.INVISIBLE);
break;
//b3 on click
case R.id.b3:
txt.setText(txt.getText().toString() + b3.getText());
b3.setVisibility(View.INVISIBLE);
break;
//here is my problem last char has deleted button of that char must be get visible
//backspace on click
case R.id.backspace:
//I want visible button has removed it text from TextView
//appear last button has clicked
txt.setText(txt.getText().toString().substring(0,txt.getText().toString().length()-1));
break;
}//end switch
} //I hope get answer in this website
}
//thank for ALL helping
You could create a Stack of pressed buttons, so that you would know in which order they are pressed:
public class MainActivity extends ... implements ...{
Stack<View> pressedButtons = new Stack<>();
...
#Override
public void onClick(View view) {
// If it is a number, not a backspace key - remember that we pressed it
if(view.getId() != R.id.backspace) {
pressedButtons.push(view);
txt.setText(txt.getText().toString() + ((Button) view).getText());
view.setVisibility(View.INVISIBLE);
}
else { // backspace key
String text = txt.getText().toString();
if(text.isEmpty())
return; // do this to prevent crash
txt.setText(text.substring(0, text.length() - 1));
// make the button visible again
View lastPressedButton = pressedButtons.pop();
lastPressedButton.setVisibility(View.VISIBLE);
}
}
}
You can try this:
case R.id.backspace:
//try like this
if(string.substring(string.length() - 1).equals(b3.getText()))
b3.setVisibility(View.VISIBLE);
...
txt.setText(txt.getText().toString().substring(0,txt.getText().toString().length()-1));

How do I prevent my submit button in android from giving me multiple scores when clicked multiple times?

Whenever I answer a question and hit the submit button, a score of 1 should show but on hitting submit button again, it keeps adding 1 to the score and more hits on the submit button keeps adding more 1 to the score. I actually don't want 1 to be added to the score every time the submit button is clicked. I do not want the score to be updated based on the number of times I hit the submit button.
package com.example.android.generalknowledge;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
int baseScore = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void submitResult(View view) {
RadioButton largestRailwayStation = (RadioButton) findViewById(R.id.largest_railway_station);
boolean answerIsLargestRailwayStation = largestRailwayStation.isChecked();
RadioButton insects = (RadioButton) findViewById(R.id.insects);
boolean answerIsInsects = insects.isChecked();
CheckBox physicsChemistry = (CheckBox) findViewById(R.id.physics_chemistry);
boolean physicsChemistryIsAnswer = physicsChemistry.isChecked();
CheckBox physiologyMedicine = (CheckBox) findViewById(R.id.physiology_medicine);
boolean physiologyMedicineIsAnswer = physiologyMedicine.isChecked();
CheckBox literature = (CheckBox) findViewById(R.id.literature);
boolean literatureIsAnswer = literature.isChecked();
CheckBox peaceEconomics = (CheckBox) findViewById(R.id.peace_economics);
boolean peaceEconomicsIsAnswer = peaceEconomics.isChecked();
RadioButton naziParty = (RadioButton) findViewById(R.id.nazi_party);
boolean answerIsNaziParty = naziParty.isChecked();
RadioButton allOfTheAbove = (RadioButton) findViewById(R.id.all_of_the_above);
boolean answerIsAll = allOfTheAbove.isChecked();
RadioButton filmFinance = (RadioButton) findViewById(R.id.film_finance);
boolean answerIsFilmFinance = filmFinance.isChecked();
EditText enterNameHere = (EditText) findViewById(R.id.name_view);
String name = enterNameHere.getText().toString();
EditText enterAnswerHere = (EditText) findViewById(R.id.answer_here);
String answer = enterAnswerHere.getText().toString();
if (enterAnswerHere.getText().toString().equals("Africa")) {
baseScore += 1 ;
}
int finalScore = calculateTotalScore(answerIsLargestRailwayStation, answerIsInsects, physicsChemistryIsAnswer,
physiologyMedicineIsAnswer, literatureIsAnswer, peaceEconomicsIsAnswer, answerIsNaziParty, answerIsAll, answerIsFilmFinance);
Toast.makeText(MainActivity.this,
name + " " + "\n" + "You have a Total Score of " + " " + finalScore + " " + "/10", Toast.LENGTH_LONG).show();
}
/**
* This method is called when any of the radio buttons in question one is selected
*/
public void onRadioButtonClickedOne(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.largest_railway_station:
if (checked)
// This is the correct answer
break;
case R.id.highest_railway_station:
if (checked)
// Wrong answer
break;
case R.id.longest_railway_station:
if (checked)
// Wrong answer
break;
case R.id.none_of_the_above:
if (checked)
//Wrong answer
break;
}
}
/**
* This method is called when any of the radio buttons in question two is selected
*/
public void onRadioButtonClickedTwo(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.behaviour_of_human_beings:
if (checked)
// Wrong answer
break;
case R.id.insects:
if (checked)
// This is the correct answer
break;
case R.id.origin_history:
if (checked)
// Wrong answer
break;
case R.id.rock_formation:
if (checked)
// Wrong answer
break;
}
}
/**
* This method is called when the checkboxes for question three are clicked
*/
public void onCheckboxThreeClicked(View view) {
//Is the button now checked?
boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox is clicked
switch (view.getId()) {
case R.id.physics_chemistry:
if (checked)
// One of the Correct answers
break;
}
switch (view.getId()) {
case R.id.physiology_medicine:
if (checked)
// One of the Correct answers
break;
}
switch (view.getId()) {
case R.id.literature:
if (checked)
// One of the Correct answers
break;
}
switch (view.getId()) {
case R.id.peace_economics:
if (checked)
// One of the Correct answers
break;
}
}
/**
* This method is called when any of the radio buttons in question four is selected
*/
public void onRadioButtonClickedFour(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.labour_party:
if (checked)
// Wrong answer
break;
case R.id.nazi_party:
if (checked)
// This is the correct answer
break;
case R.id.leading_party:
if (checked)
// Wrong answer
break;
case R.id.democratic_party:
if (checked)
// Wrong answer
break;
}
}
/**
* This method is called when any of the radio buttons in question six is selected
*/
public void onRadioButtonClickedSix(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.develop_telescope:
if (checked)
// Wrong answer
break;
case R.id.discovered_jupiter:
if (checked)
// Wrong answer
break;
case R.id.movement_of_pendulum:
if (checked)
// Wrong answer
break;
case R.id.all_of_the_above:
if (checked)
// This is the correct answer
break;
}
}
/**
* This method is called when any of the radio buttons in question seven is selected
*/
public void onRadioButtonClickedSeven(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.foreign_finance:
if (checked)
// Wrong answer
break;
case R.id.film_finance:
if (checked)
// This is the correct answer
break;
case R.id.federation_football:
if (checked)
// Wrong answer
break;
case R.id.none:
if (checked)
// Wrong answer
break;
}
}
private int calculateTotalScore(boolean questionOneAnswer, boolean questionTwoAnswer, boolean questionThreeAnswer1,
boolean questionThreeAnswer2, boolean questionThreeAnswer3, boolean questionThreeAnswer4,
boolean questionFourAnswer, boolean questionSixAnswer, boolean questionSevenAnswer) {
if (questionOneAnswer) {
baseScore += 1 ;
}
if (questionTwoAnswer) {
baseScore += 1 ;
}
if (questionThreeAnswer1) {
baseScore += 1 ;
}
if (questionThreeAnswer2) {
baseScore += 1 ;
}
if (questionThreeAnswer3) {
baseScore += 1 ;
}
if (questionThreeAnswer4) {
baseScore += 1 ;
}
if (questionFourAnswer) {
baseScore += 1 ;
}
if (questionSixAnswer) {
baseScore += 1 ;
}
if (questionSevenAnswer) {
baseScore += 1 ;
}
// EditText enterAnswerHere = (EditText) findViewById(R.id.answer_here);
// String answer = enterAnswerHere.getText().toString();
// {
// if (answer == "Africa") {
// baseScore = baseScore + 1;
// }
// }
return baseScore;
}
}
We can achieve by 2 ways,
You can diable the button by button.setEnable(false); once user click for for time
In your case if you don't have button object so you can use one global boolean and make that as false default and once user click for first time do the process and make that boolean as true, from next time check if the boolean is true just return it.
private boolean mIsSubmited = false;
public void submitResult(View view) {
if(mIsSubmited) {
return;
}
mIsSubmited = true;
RadioButton largestRailwayStation = (RadioButton) findViewById(R.id.largest_railway_station);
// Remaining code..
}
You can disable the submit button once it is clicked. For eg:
onclick() {
submitbutton.setEnabled(false);
}
Prevent user to click on submit again and again.
You can enable it back using:
submitbutton.setEnabled(true);
You can declare a Boolean globally and set it to false at first.
then on button click you can turn its value to true.
on the button click you can check if its false then only to increase the score.
You can use handler for this may be there is better solution then this.
Handler mHandler=new Handler();
//now in your click listener
mHandler.removeCallbacks(mRunnable);//
mHandler.postDelayed(mRunnable, 500);
Runnable mRunnable =new Runnable() {
#Override
public void run() {
//calculate it
}
};
//Wait for half sec before calculating the result if user clicked before then stop runnable from calcualting and again go for calculation.
Hope it helps.

Making Quiz App in Android with Radio Buttons

I'm making a Quizz App for Android with 10 Questions, all of them with 4 Radio Buttons, and one button at the end to show the score. The problem is when I choose the correct answer it gives 5 points, but if I check another radio button the points will stay 5 and if I press again it sums 5. What is the best way to code this?
Here is the code:
package com.example.android.quizproject;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int points = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void firstRadioButtons (View view){
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.questionOneA:
if (checked)
points += 0;
break;
case R.id.questionOneB:
if (checked)
points += 0;
break;
case R.id.questionOneC:
if (checked)
points += 5;
break;
case R.id.questionOneD:
if (checked)
points += 0;
break;
}
}
public void showScore (View view) {
TextView scoreTextView = (TextView) findViewById(R.id.score);
scoreTextView.setText(" " + points);
}
}
You can make use of a counter vvariable which checks if the question has been previousy answered or not. Modify part of your code to this
public void firstRadioButtons (View view){
boolean checked = ((RadioButton) view).isChecked();
int count=0;
switch (view.getId()) {
case R.id.questionOneA:
if (checked)
{
if(count!=0){
points-=5;
count=0;
}
}
break;
case R.id.questionOneB:
if (checked)
{
if(count!=0){
points-=5;
count=0;
}
}
break;
case R.id.questionOneC:
if (checked){
points += 5;
count+=1;}
break;
case R.id.questionOneD:
if (checked)
{
if(count!=0){
points-=5;
count=0;
}
}
break;
}
}
Actually, the way you described it, it's common sense. If you click the right answer once, it will set it to 5, but if you press any other it will add 0 to it.
In general, it will print out 5 since you got the answer correct once, and the other questions are set to 0. There's really nothing to fix here, it's kind of common sense that your variable wouldn't read other than 5. Just like Abhriya said, you could add a counter increment value as done in ( her / his ) example.

Rolling a dice based on number of sides

EDIT: See included error log.
I am trying to create a simple app to roll different sided dice in Android Studio.
This is my code so far:
MainActivity.java
package com.example.thomb.tutorialspoint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.buttonRoll);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int roll = RollDice(sidesChosen);
TextView tv1 = (TextView)findViewById(R.id.textView);
tv1.setText(roll);
setContentView(tv1);
}
});
}
public int sidesChosen;
public int RollDice(int sides) {
Random r = new Random();
return r.nextInt(sides)+1;
} //method
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radioButtonD4:
if (checked)
sidesChosen = 4;
break;
case R.id.radioButtonD6:
if (checked)
sidesChosen = 6;
break;
case R.id.radioButtonD8:
if (checked)
sidesChosen = 8;
break;
case R.id.radioButtonD10:
if (checked)
sidesChosen = 10;
break;
case R.id.radioButtonD12:
if (checked)
sidesChosen = 12;
break;
case R.id.radioButtonD20:
if (checked)
sidesChosen = 20;
break;
} //switch
} //method
} //class
This is how the layout looks like:
http://i.imgur.com/IeIbMlz.png
The app crashes when i click the roll button, but I've no idea why. The ID's are all correct and the radio buttons works as expected.
I am using API level 25. I am fairly new to Java, but I am quite familiar with C#, so the problem may lie in the code syntax, although Android Studio reports no errors. Let me know if you need to see the XML for the layout as well.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.thomb.tutorialspoint, PID: 5029
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:4310)
at android.view.ViewGroup.addView(ViewGroup.java:4146)
at android.view.ViewGroup.addView(ViewGroup.java:4087)
at android.view.ViewGroup.addView(ViewGroup.java:4060)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:279)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:145)
at com.example.thomb.tutorialspoint.MainActivity$1.onClick(MainActivity.java:25)
at android.view.View.performClick(View.java:5280)
at android.view.View$PerformClick.run(View.java:21239)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
setText() is a overloaded method with two types: one that takes in a String, the other an int. The int here should be string resource ID. This is where your error is. In the code below you're using setText(int) but not passing a valid string resource ID.
int roll = RollDice(sidesChosen);
...
tv1.setText(roll);
Do setText(String.valueOf(roll) to convert it to a String first
EDIT after log post:
The cause of your error is that you're passing 0 to the nextInt() method. This might happen because you've never selected a RadioButton (sidesChosen is 0 by default) or that even after selecting a RadioButton, none of the cases of the switch is entered.
EDIT after second log post: (...)
Remove setContentView(tv1); This is used to attach a layout to an activity. Why are you using it here?
It seems, that you pass 0 to the Random.nextInt() method, which is not allowed.
java.lang.IllegalArgumentException: n <= 0: 0
at java.util.Random.nextInt(Random.java:182)
This happens, if none of your case branches is reached. So it seems, there is something wrong with how you handle the radio button clicks.

basic android: syntax for switch statement instead of else-if

I am working on an android beginner's tutorial that is a tip calculator. It runs properly, but I was wondering how to replace the else-if statement with a switch statement. Not that it is that important for the purposes of this program, but I'm just trying to wrap my mind around the syntax.
package com.android.tipcalc;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Button;
import android.widget.RadioButton;
import android.view.View;
public class tipcalc extends Activity
{
private EditText txtbillamount;
private EditText txtpeople;
private RadioGroup radiopercentage;
private RadioButton radio15;
private RadioButton radio18;
private RadioButton radio20;
private TextView txtperperson;
private TextView txttipamount;
private TextView txttotal;
private Button btncalculate;
private Button btnreset;
private double billamount = 0;
private double percentage = 0;
private double numofpeople = 0;
private double tipamount = 0;
private double totaltopay = 0;
private double perperson = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
private void initControls()
{
txtbillamount = (EditText)findViewById(R.id.txtbillamount);
txtpeople = (EditText)findViewById(R.id.txtpeople);
radiopercentage = (RadioGroup)findViewById(R.id.radiopercentage);
radio15 = (RadioButton)findViewById(R.id.radio15);
radio18 = (RadioButton)findViewById(R.id.radio18);
radio20 = (RadioButton)findViewById(R.id.radio20);
txttipamount=(TextView)findViewById(R.id.txttipamount);
txttotal=(TextView)findViewById(R.id.txttotal);
txtperperson=(TextView)findViewById(R.id.txtperperson);
btncalculate = (Button)findViewById(R.id.btncalculate);
btnreset = (Button)findViewById(R.id.btnreset);
btncalculate.setOnClickListener(new Button.OnClickListener() {
public void onClick (View v){ calculate(); }});
btnreset.setOnClickListener(new Button.OnClickListener() {
public void onClick (View v){ reset(); }});
}
private void calculate()
{
billamount=Double.parseDouble(txtbillamount.getText().toString());
numofpeople=Double.parseDouble(txtpeople.getText().toString());
if (radio15.isChecked()) {
percentage = 15.00;
} else if (radio18.isChecked()) {
percentage = 18.00;
} else if (radio20.isChecked()) {
percentage = 20.00;
}
tipamount=(billamount*percentage)/100;
totaltopay=billamount+tipamount;
perperson=totaltopay/numofpeople;
txttipamount.setText(Double.toString(tipamount));
txttotal.setText(Double.toString(totaltopay));
txtperperson.setText(Double.toString(perperson));
}
private void reset()
{
txtbillamount.setText("");
txtpeople.setText("");
radiopercentage.clearCheck();
radiopercentage.check(R.id.radio15);
txttipamount.setText("...");
txttotal.setText("...");
txtperperson.setText("...");
}
}
What the people above me said is correct, but for the sake of using a switch statement for the hell of it, you could set an OnCheckedChangedListener on your RadioGroup, then use a class like this:
private class MyCheckedChangedListener implements OnCheckedChangeListener {
#Override
public void onCheckedChanged( RadioGroup group, int checkedId ) {
switch (checkedId) {
case R.id.radio15:
percentage = 15f;
break;
case R.id.radio18:
percentage = 18f;
break;
case R.id.radio20:
percentage = 20f;
break;
}
}
}
A switch is used on one variable - i.e. you have x, which can equal 3,5 or 7. Then you switch x and give several cases - what to do on each possible value (you can also have a default case, when none of the given values match). In your case, you're checking several different variables, so if ... else if ... else is the correct method. You can, of course, make the radio boxes set a shared variable, which you can then switch.
If you're talking about the if-else statements in calculate(), you can't replace it directly with a switch statement. The case values in a switch statement need to be compile-time constants (either integers or enum values). Besides, the if-else here perfectly expresses the logic of what you are trying to do.
You could compute a "switch test value" based on the states of radio15, radio18, and radio20 (say, an integer from 0 to 8, based on the eight possible combinations of values) and switch on that, but I would strongly recommend against such an approach. Not only would it needlessly complicate and obscure the logic of what's going on, you would be cursing yourself if you needed to maintain the code six months from now after you had forgotten the clever trick.

Categories

Resources