[英]How to pass data from a class and used in another class for calculation
我正在嘗試執行此功能,在這里我計算BMIcalculation類中所需的卡路里,然后我創建了另一個名為CalorieIntake的類,在這里我將計算總卡路里攝入量。 (我通過擴展BMIcalculation類來實現。)
然后,當我單擊“檢查”按鈕時,它應該在這兩個值之間進行比較並顯示解釋。 但是,我一直在'exploreDiff(float diffValue)'部分收到錯誤消息,其中提到它必須以String值返回。
這是我的代碼。.pls幫助我檢查問題出在哪里。 還是有更好的方法呢? 請給我建議。 非常感謝..
public class CalorieIntake extends BMIcalculation {
TextView counter1;
Button compare;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.form_calorieintake2);
Button btn_calcIntake = (Button) findViewById(R.id.button_calcIntake);
btn_calcIntake.setOnClickListener(btnListener_calcIntake);
counter1 = (TextView) findViewById(R.id.textView_totalCalorieIntake);
Button compare = (Button) this.findViewById(R.id.checkIntake);
compare.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
try {
if ((!counter1.equals("")) && (!caloriesresult.equals("")))
{
TextView compareText = (TextView)findViewById(R.id.compareLabel);
EditText counter1E = (EditText) findViewById(R.id.textView_totalCalorieIntake);
EditText caloriesresultE = (EditText)findViewById(R.id.caloriesText);
float calorieIntake = Float.parseFloat(counter1E.getText().toString().trim());
float calorieNeed = Float.parseFloat(caloriesresultE.getText().toString().trim());
float diffValue = calDiff(calorieIntake, calorieNeed);
String calInterpretation = interpretDiff(diffValue);
compareText.setText("Difference of" + diffValue + " : " + calInterpretation);
}
}catch (Exception k)
{ System.out.println(k);
Toast.makeText(CalorieIntake.this, "Error", Toast.LENGTH_SHORT).show();
}
}
private String interpretDiff(float diffValue)
{
if (diffValue < 100)
{
return "Eat more";
}
}
private float calDiff(float calorieIntake, float calorieNeed) {
return (float) (calorieIntake - calorieNeed);
}
});
}
如果diffValue不小於100,會發生什么情況? 你什么也沒回報。 但是,java要求您返回某些內容,因為這就是該方法的聲明所隱含的含義。
一個解決方案是:
private String interpretDiff(float diffValue)
{
if (diffValue < 100)
return "Eat more";
return "Eat less";
}
如果diffValue不小於100,則在此不需要else語句,因為僅當diffValue> = 100時才調用第二個return語句(因為命中return語句會退出該方法)。
關於引發異常和調用Toast錯誤的問題,僅可能由於以下代碼而發生:
TextView compareText = (TextView)findViewById(R.id.compareLabel);
EditText counter1E = (EditText) findViewById(R.id.textView_totalCalorieIntake);
EditText caloriesresultE = (EditText)findViewById(R.id.caloriesText);
float calorieIntake = Float.parseFloat(counter1E.getText().toString().trim());
float calorieNeed = Float.parseFloat(caloriesresultE.getText().toString().trim());
float diffValue = calDiff(calorieIntake, calorieNeed);
String calInterpretation = interpretDiff(diffValue);
compareText.setText("Difference of" + diffValue + " : " + calInterpretation);
假設findViewById中沒有問題,則錯誤可能是由於獲取counter1E,cabatesresultE(如果為空)的文本而引起的。 如果這些都不為空,則檢查以確保callDiff和interpretDiff中沒有錯誤。 最后,確保compareText不為null。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.