在Eclipse中为硬币翻转Java设置
问题描述:
我需要使用java在eclipse中投掷硬币的代码,代码需要包含用户在硬币上的输入,并在代码启动投掷硬币后调用硬币。在Eclipse中为硬币翻转Java设置
这里是我到目前为止的代码:
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();
但我不知道下一步该怎么做。
答
你必须产生一个随机数0 or 1
,然后与用户输入进行比较,然后根据比较结果进行。
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.");
}
答
你可以做这样的事情。
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");
}
到目前为止您尝试了什么? –
好的,你有用户输入。接下来是产生一个随机数来翻转硬币?你可以使用'Math.random()',或使用'Random'类。 –
如果你在这里搜索'java coin flip',你会发现一些类似的问题和答案,可能会给你一些有用的想法 –