java – Android应用程序Toast混乱
作者:互联网
我的应用程序是一个测验应用程序,其中有一部分在用Toast回答所有问题之后吐出了用户纠正的百分比问题.
吐司正在出现,但百分比总是为0.
我面前有一些日志消息:
Log.i("MainActivity", "Amount i got right "+Integer.toString(right));
Log.i("MainActivity", "total is "+Integer.toString(total));
Toast.makeText(this, "You answered " + (right/total)*100 + "% of questions correct", Toast.LENGTH_SHORT).show();
在日志中它显示“I / MainActivity:我正确的数量4
总共6“
为什么吐司百分比为0?
这是功能:
int i = 0;
int total = mQuestionBank.length;
check = true;
right = 0;
while (i<total && check){
if(mQuestionBank[i].isAlreadyAnswered()){
if(mQuestionBank[i].isAnswerTrue()){
right+=1;
check = true;
}
}else{
check = false;
}
i++;
}
if(check) {
double percent = (right / total) * 100;
Log.i("MainActivity", "Amount i got right "+Integer.toString(right));
Log.i("MainActivity", "total is "+Integer.toString(total));
Toast.makeText(this, "You answered " + (right/total)*100 + "% of questions correct", Toast.LENGTH_SHORT).show();
}else {
int question = mQuestionBank[mCurrentIndex].getTextResId();
mQuestionTextView.setText(question);
mTrueButton.setEnabled(!mQuestionBank[mCurrentIndex].isAlreadyAnswered());
mFalseButton.setEnabled(!mQuestionBank[mCurrentIndex].isAlreadyAnswered());
}
吐司说“你回答了0%的问题是正确的”
解决方法:
代码没问题.你只需要一个简单的修改.
试试这个 :
double percent = (right*100)/total ;
要么 ,
double percent = ((double)right/total)*100 ;
希望这会奏效.
更新:
为什么你的代码不起作用?
例如,取右= 5,总数= 10.因为变量right和true是整数所以right / total将为0,因为它们将返回一个整数值和后面的值.不被视为整数值.
要解决这个问题,您可以将right和total视为双变量,或者将右侧变为double.并首先解释了公式. ***因为右* 100 = 500和(右* 100)/总= 500/10 = 50.
标签:java,android,android-toast 来源: https://codeday.me/bug/20190607/1194461.html