gpt4 book ai didi

java - 如何使用数组编写程序,其中用户输入数字,程序返回相应的结果

转载 作者:太空宇宙 更新时间:2023-11-04 09:46:07 26 4
gpt4 key购买 nike

我有一个学校项目,用户将在其中输入一个数字,然后程序显示与该数字对应的卡片。我不知道应该如何处理这个项目。我使用数组吗?

该项目要求我使用一副纸牌作为数组的内容。程序的输出应该是:

Enter card number (1-52): 1 The card you picked is: Ace of Clubs.

Enter Card Number (1-52): 11 The card you picked is Jack of Clubs

Enter Card Number (1-52): 14 The card you picked is Ace of Diamonds

Enter Card Number (1-52): 52 The card you picked is King of Spades

public class Deck {
public static void main(String[] args) {
ArrayList[][] table = new ArrayList[4][13];
String[] suits= {"Clubs", "Diamonds", "Hearts", "Spades"};
String[] ranks= {"Ace","2","3","4","5","6","7","8","9","10","Jack", "Queen","King"};

for (int i=0; i<4; ++i)
for (int j=0; i<13; ++i) {

}
}
}

最佳答案

模数运算符在这里派上用场:

String[] suits= { "Clubs", "Diamonds", "Hearts", "Spades" };
String[] ranks= { "Ace","2","3","4","5","6","7","8","9","10","Jack", "Queen","King" };

for (int i=0; i < 52; ++i) {
String suit = suits[i / 13];
String rank = ranks[i % 13];

System.out.println("Card: " + rank + " of " + suit);
}

Card: Ace of Clubs
Card: 2 of Clubs
Card: 3 of Clubs
Card: 4 of Clubs
...
Card: Jack of Spades
Card: Queen of Spades
Card: King of Spades

这里的技巧是,套装的索引是由我们已经消耗了多少 13 决定的。这可以通过将单个索引i除以13来获得。排名可以通过索引除以13的余数来确定。

关于java - 如何使用数组编写程序,其中用户输入数字,程序返回相应的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55410931/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com