I'm trying to make a basic MineSweeper game in Java.
I'm making a method which calculates the amount of mines that will be in the field, depending on the choice of difficulty made by the user.
Let's say the field has a total of 64 cells, and the user chose an "Advanced" difficulty. Let's say that 50% of the cells will be filled with mines, so there would be a total of 32 mines (field total magnitude / 100 * 50).
The problem I'm having is that the returning value is always 0.
This is the method I'm writing:
public int calculateMines ()
{
int mines;
mines = 0;
float probability;
probability = (float) 0.0;
int magnitude;
magnitude = 0;
char dificulty;
dificulty = '0';
magnitude = this.getMagnitude();
dificulty = this.getDificulty();
switch (dificulty)
{
case 'B':
case 'b':
probability = (float) ((magnitude/100) * 20);
break;
case 'I':
case 'i':
probability = (float) ((magnitude/100) * 30);
break;
case 'A':
case 'a':
probability = (float) ((magnitude/100) * 50);
break;
default:
probability = -1;
System.err.println("EEROR!");
break;
}
mines = (int) probability;
return mines;
}
What am I doing wrong?
If magnitude
is less than 100
then probability
will be 0
due to integer division. You could do
probability = (float) ((magnitude/100.0) * 20);