如果语法不在这里我很抱歉,特别是关于布尔值:
public class WeightConverter extends Activity implements OnClickListener, OnCheckedChangeListener {
Button convertWeight;
TextView conversionResults;
EditText enterWeight;
RadioGroup weightPicker;
RadioButton radKG, radLB;
double weightValue, convertedWeight;
String weightString;
String measurement;
Boolean weightSwitch;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.weightconverter);
initializeVariables();
weightSwitch = false;
radKG.setChecked(true);
}
private void initializeVariables() {
convertWeight = (Button) findViewById(R.id.btnConvertWeight);
conversionResults =(TextView) findViewById(R.id.tvWeightConversion);
enterWeight =(EditText) findViewById(R.id.etWeightToConvert);
weightPicker = (RadioGroup) findViewById(R.id.rgWeightType);
radKG = (RadioButton) findViewById(R.id.radKG);
radLB = (RadioButton) findViewById(R.id.radLB);
convertWeight.setOnClickListener(this);
weightPicker.setOnCheckedChangeListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnConvertWeight:
if (weightSwitch = true){
convertedWeight = weightValue /2.2;
measurement = "Kilograms";
}else{
convertedWeight = weightValue *2.2;
measurement = "Pounds";
}
conversionResults.setText(weightValue + " = " + String.valueOf(convertedWeight) + " " + measurement);
break;
}
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
weightValue = Double.parseDouble(enterWeight.getText().toString());
switch (checkedId) {
case R.id.radKG:
weightSwitch = true;
break;
case R.id.radLB:
weightSwitch = false;
break;
}
}
}
根据用户是否选择其中一种布尔类型,应执行不同的计算,但只有转换为磅才有效。
答案 0 :(得分:0)
您正尝试将boolean
值与此行中的=
运算符进行比较:
if (weightSwitch = true){
但=
是赋值运算符,因此weightSwitch
始终为true
。
使用==
来比较boolean
或更好的值:
if (weightSwitch)
因为它已经是boolean
值。