Android app Toast confusion

1h1h1h1h1h1h1h :

My app is a quiz app, in it there's a part that spits out a percent of questions the user got correct after answering all the questions as a Toast.

The toast is showing up but the percentage is always coming up as 0.

I have some log messages just infront:

        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();

In the log it says "I/MainActivity: Amount i got right 4 total is 6"

Why is the toast percentage coming as 0??

here's the function:

    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());
    }

The Toast says "You answered 0% of the questions correct"

Sudipta Basak :

The code is OK . You just need a simple modification . Try this :

double percent = (right*100)/total ;

or ,

double percent = ((double)right/total)*100 ;

Hope this will work .


Update :

Why your code was not working ?

As a example take right = 5 and total = 10 . As the variable right and true are integers so right/total will be 0 zero always because they will return a integer value and the value after . is not considered in integer value . To solve the problem you can take right and total as double variable or cast the right as double . And the first explained formula . ***Because right*100 = 500 and (right*100)/total = 500/10 = 50 .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=76813&siteId=1