在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(); 

但我不知道下一步该怎么做。

+1

到目前为止您尝试了什么? –

+0

好的,你有用户输入。接下来是产生一个随机数来翻转硬币?你可以使用'Math.random()',或使用'Random'类。 –

+0

如果你在这里搜索'java coin flip',你会发现一些类似的问题和答案,可能会给你一些有用的想法 –

我不明白你的问题,而是: -start正常,(类,主要方法等) -make变量(INT硬币等) 次使用进口java.util.Scanner中,和INT X = scanner.nextInt()来获取用户输入(什么?) 次使用的Math.random随机折腾,也许0.5 +是头 - 什么你永远得到=硬币 -refine你质疑

+0

我需要用户输入猜测什么时候硬币翻转 – Carlos

+0

头部需要是1和如果(选择> 1)不会导致代码停止,因为尾部为0,并且如果被调用的0或尾部会停止代码并且说0是一个尾部,则尾部需要为0 – Carlos

你必须产生一个随机数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"); 

} 
+0

无效输入 – Carlos

+0

@Carlos为什么它会停止在0条件选择> 1 – mhasan

+0

这个代码是随机还是不是? – Carlos