简体   繁体   中英

Setup for Coin Flip Java in Eclipse

I need help with starting code for a coin toss in eclipse using java, the code needs to contain user input on the coin and call the coin once the code initiates the tossing of the coin.

Here's the code I have so far:

Scanner input = new Scanner(System.in);
int choice;
int heads = 1;
int tails = 0;
System.out.print("Please call the toss, heads or tails: ");
choice = input.nextInt();

But I'm not sure what to do next.

You have to generate a random number 0 or 1 and then compare with user input and do the rest based on comparison.

Scanner input = new Scanner(System.in);
int choice;
System.out.print("Please call the toss, heads(1) or tails(0): ");
choice = input.nextInt();
int randomNum = Random.nextInt(2) + 1;
if(randomNum == choice){
     System.out.print("You win.");
}
else{
     System.out.print("You lost.");
}

You can do something like this.

Scanner input = new Scanner(System.in);
int choice;
int heads = 1;
int tails = 0;
System.out.print("Please call the toss, heads or tails: ");
choice = input.nextInt();
if(choice > 1)
{
   System.out.println("Invalid choice");
}
//Get the random number either between 0 or 1 
int randomNum = ThreadLocalRandom.current().nextInt(tails, heads + 1);
if(randomNum  == choice)
{
   System.out.println("You win");
}
else
{
   System.out.println("You lose");

}

我没有得到你的问题,但是: - 正常启动,(类,主要方法等) - 制作一个变量(int coin 等) - 使用 import java.util.Scanner 和 int x = scann.nextInt() 来获取用户输入(为了什么?) - 使用 math.random 进行随机抛掷,也许 0.5 + 是正面 - 你得到什么 = 硬币 - 细化你的问题

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM