2017-03-10 83 views
-4

我需要使用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',你會發現一些類似的問題和答案,可能會給你一些有用的想法 –

回答

-1

我不明白你的問題,而是: -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

你必須產生一個隨機數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."); 
} 
0

你可以做這樣的事情。

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