Richard Thomas - 9 months ago 51

Java Question

I'm new to Android and I'm having trouble with a maths app I am creating.

The basic premise is to present the user with 2 numbers between 0 and 20 (questionTextView) then show the user a grid containing 3 incorrect answers and 1 correct answer. The user then clicks on the correct answer.

The issue I'm having is that the correct answer is not displaying to 2 decimal points.

E.g. Question: 4 / 7

Answer 1: 12.59

Answer 2: 15.99

Answer 3: 9.93

Answer 4: 0 (Should be 0.57)

I don't understand why the correct answer is not displaying properly as I have cast both ints to doubles and included decimal formatting.

I've tried Math.round(), but I couldn't get this to work - perhaps due to the way I have generated the questions within a for loop????

The incorrect answers display properly.

Any assistance would be greatly appreciated.

Here is my code:

`private static DecimalFormat df2 = new DecimalFormat("#.##");`

public void generateQuestion(){

//Create 2 random numbers between 0 and 20.

Random rand = new Random();

int a = rand.nextInt(21);

int b = rand.nextInt(21);

if (a==b){

b = rand.nextInt(21);

}

questionTextView.setText(Integer.toString(a) + " / " + Integer.toString(b));

/*Create a random number between 0 and 3 to determine the grid square of

the correct answer */

locationOfCorrectAnswer = rand.nextInt(4);

//Calculate the correct answer.

double correctAnswer = (int)(((double)a/(double)b));

//Generate an incorrect answer in case the correct answer is

randomly generated.

double inCorrectAnswer;

/*Loop through each square and assign either the correct answer or

a randomly generated number. */

for (int i=0; i<4; i++){

if (i == locationOfCorrectAnswer){

answers.add(df2.format(correctAnswer).toString());

} else {

inCorrectAnswer = 0.05 + rand.nextDouble() *20.0;

while (inCorrectAnswer == correctAnswer){

inCorrectAnswer = 0.05 + rand.nextDouble() *20.0;

}

answers.add(df2.format(inCorrectAnswer).toString());

}

}

//Assign an answer to each of the buttons.

button0.setText((answers.get(0)));

button1.setText((answers.get(1)));

button2.setText((answers.get(2)));

button3.setText((answers.get(3)));

Answer

`(((double)a/(double)b))`

This will give you = 0.57 and then this `(int)`

this will convert 0.57 to 0 here `(int)(((double)a/(double)b));`

because integer can only hold `whole numbers`

hence decimal values will be truncated.

use this to keep decimal values

```
double correctAnswer = (((double)a/(double)b));
```