![](/img/trans.png)
[英]How to randomly select a string between two strings from ENUM in java?
[英]How do I randomly choose between two enum values from a seperate class file
所以我需要在其中創建一個帶有枚舉的類,然后使用第二個類隨機選擇其中一個枚舉值並按照用戶的需要多次執行。
這是主要代碼
while (loop){
System.out.println("Enter the number of times you want to toss the coin, enter '0' to end the program: ");
num = s.nextInt();
int tails = 0;
int heads = 0;
if (num == 0){
loop = false;
continue;
}
else if (num < 0){
System.out.println("That's a negative number");
continue;
}
for (int count = 0; count < num; count++)
{
if (rand.nextInt(2) == 0)
tails = tails + 1;
else
heads = heads + 1;
}
System.out.println("Heads: " + heads + " Tails: " + tails);
}
然后這是枚舉代碼
public class Coin{
public enum CoinEnum {
HEADS,TAILS;
}
}
我刪掉了一些東西,因為它不需要。 我想我對如何隨機選擇有一般的想法,你可以看到我已經寫了一個關於如果沒有枚舉值如何做的快速計算,但我不知道如何從我的主程序訪問枚舉值,我試着讓這個類成為一個包但是沒有用,我只是不確定如何。 任何幫助都會很棒。
謝謝
以下代碼應該可以工作 - 隨機生成HEAD或TAIL枚舉; 評論添加到代碼中。 編輯將其更改為一個獨立的工作示例。
public class CoinEnumDemo {
public static void main(String[] args) {
// print 10 random values
for (int i = 0; i < 10; i++) {
int val = (int) Math.round(Math.random());
System.out.println(CoinEnum.values()[val]);
}
}
enum CoinEnum {
HEAD, TAIL;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.