Calculating percent "x/y * 100" always results in 0?
Posted
by
Patrick Beninga
on Stack Overflow
See other posts from Stack Overflow
or by Patrick Beninga
Published on 2012-11-12T04:51:22Z
Indexed on
2012/11/12
4:59 UTC
Read the original article
Hit count: 130
In my assignment i have to make a simple version of Craps, for some reason the percentage assignments always produce 0 even when both variables are non 0, here is the code.
import java.util.Random;
Header, note the variables
public class Craps {
private int die1, die2,myRoll ,myBet,point,myWins,myLosses;
private double winPercent,lossPercent;
private Random r = new Random();
Just rolls two dies and produces their some.
public int roll(){
die1 = r.nextInt(6)+1;
die2 = r.nextInt(6)+1;
return(die1 + die2);
}
The Play method, this just loops through the game.
public void play(){
myRoll = roll();
point = 0;
if(myRoll == 2 ||myRoll == 3 || myRoll == 12){
System.out.println("You lose!");
myLosses++;
}else if(myRoll == 7 || myRoll == 11){
System.out.println("You win!");
myWins++;
}else{
point = myRoll;
do {
myRoll = roll();
}while(myRoll != 7 && myRoll != point);
if(myRoll == point){
System.out.println("You win!");
myWins++;
}else{
System.out.println("You lose!");
myLosses++;
}
}
}
This is where the bug is, this is the tester method.
public void tester(int howMany){
int i = 0;
while(i < howMany){
play();
i++;
}
bug is right here in these assignments statements
winPercent = myWins/i * 100;
lossPercent = myLosses/i* 100;
System.out.println("program ran "+i+" times "+winPercent+"% wins "+ lossPercent+"% losses with "+myWins+" wins and "+myLosses+" losses");
}
}
© Stack Overflow or respective owner