2015-10-14 143 views
1

我试图创建一个程序来刺激从卡组中挑选一张牌。我试过使用Random类选择suitrank,但我无法使它工作。这是我的代码到目前为止。如何从列表中选择一个随机字符串

String[] rank = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"}; 
    int idx = new Random().nextInt(rank.length); 
    String random = (rank[idx]); 

    String[] suit = {"Clubs", "Diamonds", "Hearts", "Spades"}; 
    int idx = new Random().nextInt(suit.length); 
    String random = (suit[idx]); 

    System.out.println("The card you picked is " + Arrays.toString(rank) + " of " + Arrays.toString(suit)); 

我确定它非常简单,但我相对较新,因此任何帮助表示赞赏!

+1

**“但我不能得到它的工作”**你可以做得比这更好:) –

+0

你有2个变量具有相同的名称idx,随机和你打印出错误的变量,应该是2随机值。 –

+0

您正在重复您的变量,'idx'和'random'使用不同的名称。 –

回答

3

你做得对。你只需要打印正确的变量:

String[] rank = // ... 
int rankIndex = new Random().nextInt(rank.length); 
String randomRank = rank[rankIndex]; 

String[] suit = // ... 
int suitIndex = new Random().nextInt(suit.length); 
String randomSuit = suit[suitIndex]; 

System.out.println("The card you picked is " + randomRank + " of " + randomSuit); 
0

请务必补充说错了,你没有包括你有什么问题。

但我期待它的下面:

1)随机字符串声明两次 2)Arrays.toString()你为什么要使用Arrays.ToString(无需

System.out.println("The card you picked is " + **Arrays.toString(rank)** + " of " + Arrays.toString(suit)); 

)?

String rankstr = (rank[idx]); 
String suitStr = (suit[idx]); 
    System.out.println("The card you picked is " + rankStr + " of " + suitStr); 
1

问题是在这里:System.out.println("The card you picked is " + Arrays.toString(rank) + " of " + Arrays.toString(suit));。您每次打印完整的物品清单。

你需要做的是将(rank[idx])(suit[idx]);放入字符串变量并打印这些变量。

String[] rank = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"}; 
    int idx = new Random().nextInt(rank.length); 
    String randomRank = (rank[idx]); 

    String[] suit = {"Clubs", "Diamonds", "Hearts", "Spades"}; 
    idx = new Random().nextInt(suit.length); 
    String randomSuit = (suit[idx]); 
    System.out.println("The card you picked is " + randomRank + " of " + randomSuit); 
0

你重复的变量名称idxrandom,选择不同的名称和输出是这样的:

System.out.println("The card you picked is " +random2+ " of " +random); 
//The card you picked is 2 of Spades 

直播Java示例:

http://ideone.com/9asht6

相关问题