Vidit Shah Vidit Shah - 3 months ago 14
Android Question

On Clicking multiple Checkbox resulting into undesired result

I would like my checkbox to show correct answer only for 2 options but if selects more than 2 options including the correct options it shows correct answer which is not the desired Result .

package com.example.vidit.project3;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.Toast;


public class question2 extends AppCompatActivity {



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question2);
}

public void submit2(View v)
{
CheckBox cb1= (CheckBox) findViewById(R.id.c1);
CheckBox cb2=(CheckBox) findViewById(R.id.c2);
CheckBox cb3=(CheckBox) findViewById(R.id.c3);
CheckBox cb4=(CheckBox) findViewById(R.id.c4);



//Show Correct option for only one combination
if(cb1.isChecked() && cb2.isChecked())
{
Toast toast = Toast.makeText(getApplicationContext(),"Whopiee! Correct Answer",Toast.LENGTH_LONG);
toast.show();
}
else if(cb1.isChecked() && cb2.isChecked() && cb3.isChecked() && cb4.isChecked())
{
Toast toast = Toast.makeText(getApplicationContext(),"Arghh! Incorrect Answer",Toast.LENGTH_LONG);
toast.show();
}
else if(cb1.isChecked() && cb2.isChecked() && cb3.isChecked())
{
Toast toast = Toast.makeText(getApplicationContext(),"Arghh! Incorrect Answer",Toast.LENGTH_LONG);
toast.show();
}
else if(cb1.isChecked() && cb2.isChecked() && cb4.isChecked())
{
Toast toast = Toast.makeText(getApplicationContext(),"Arghh! Incorrect Answer",Toast.LENGTH_LONG);
toast.show();
}
else
{
Toast toast = Toast.makeText(getApplicationContext(),"Arghh! Incorrect Answer",Toast.LENGTH_LONG);
toast.show();
}

}

public void toQuestion3(View v)
{
Intent intent = new Intent(this,question3.class);
startActivity(intent);

}



}


Yours Sincerely,
Vidit Shah

Answer

Make your first if like this:

if(cb1.isChecked() && cb2.isChecked() && !cb3.isChecked() && !cb4.isChecked()){
        Toast toast =  Toast.makeText(getApplicationContext(),"Whopiee! Correct Answer",Toast.LENGTH_LONG);
        toast.show();
}

You could summarize your code by doing this:

boolean correct = cb1.isChecked() && cb2.isChecked() && !cb3.isChecked() && !cb4.isChecked();
String message = correct ? "Whopiee! Correct Answer" : "Arghh! Incorrect Answer";
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();