I want a random number, either 0 or 1 and then that will be returned to main() as in my code below.
import java.util.Scanner;
public class Exercise8Lab7 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numFlips = 0;
int heads = 0;
int tails = 0;
String answer;
System.out.print("Please Enter The Number Of Coin Tosses You Want: ");
numFlips = input.nextInt();
for(int x = 1;x <= numFlips; x++){
if(coinToss() == 1){
answer = "Tails";
tails++;
}
else{
answer = "Heads";
heads++;
}
System.out.print("\nCoin Toss " + x + ": " + answer);
}
System.out.println("\n\n====== Overall Results ======" +
"\nPercentage Of Heads: " + (heads/numFlips)*100 + "\nPercentage Of Tails: " + (tails/numFlips)*100);
}
public static int coinToss(){
double rAsFloat = 1 * (2 + Math.random( ) );
int r = (int)rAsFloat;
return r;
}
}
Many solutions had been suggested to use the util.Random option which I have done and works perfectly but I want to sort out why I can't get this to work. Obviously I want the number to be an int myself so I convert it to an int after the random number has been generated. But no matter what I add or multiply the Math.random() by, it will always all either be Heads or all either be Tails. Never mixed.
The rand( ) function generates random numbers between 0 and 1 that are distributed uniformly (all numbers are equally probable). If you attempt the extra credit, you likely will need to use the rand( ) function. If you want to generate random numbers from 0 to 10, you multiply the random number by 10.
The Math. random() method returns a random number from 0 (inclusive) up to but not including 1 (exclusive).
random() method returns a pseudorandom double type number greater than or equal to 0.0 and less than 1.0. .
The random() function allows us to generate random numbers between 0 and 1 (generates floating-point random numbers). It is a default random generator function. The uniform() function generates random numbers between specified ranges rather than 0 and 1 (generates floating-point random numbers).
Try this) It will generate number 0 or 1
Math.round( Math.random() ) ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With