gpt4 book ai didi

java - 只是另一个新手 Java 编码器请求批准

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:42:46 24 4
gpt4 key购买 nike

所以...我最近正在学习一些 Java,如果您愿意,我希望您能帮助我完成我的第一个程序。这是我的程序代码,它显示牌组中的随机卡片。

我的问题如下:有没有更聪明的方法让这个程序运行?

/*
* File: RandomCard.java
* ----------------
* This program display random card from the deck with it's own rank
* (Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Quenn, King) and suit (Clubs,
* Diamonds, Hearts, Spades).
*/

import acm.program.*;
import acm.util.*;

public class RandomCard extends ConsoleProgram {
/* Run the program */
public void run() {
println("This program displays a random card from the deck.");
println("You random card is " + getRandomRank() + " "
+ getRandomSuit() + ".");
}

/* Get random rank for the card. */
private String getRandomRank() {
int rank = rgen.nextInt(1, 13);
switch (rank) {
case 1: return "Ace";
case 2: return "2";
case 3: return "3";
case 4: return "4";
case 5: return "5";
case 6: return "6";
case 7: return "7";
case 8: return "8";
case 9: return "9";
case 10: return "10";
case 11: return "Jack";
case 12: return "Queen";
case 13: return "King";
default: return null;
}
}

/* Create random suit from within Clubs, Diamonds, Hearts and Spades. */
private String getRandomSuit() {
int suit = rgen.nextInt(0, 3);
switch (suit) {
case 0: return "Clubs";
case 1: return "Diamonds";
case 2: return "Hearts";
case 3: return "Spades";
default: return null;
}
}

/* Create an instance variable for the random number generator */
private RandomGenerator rgen = new RandomGenerator();
}

最佳答案

一个小的改进:任何时候你有这样的 switch 语句:

 switch (rank) {
case 1: return "Ace";
case 2: return "2";
case 3: return "3";
case 4: return "4";
case 5: return "5";
case 6: return "6";
case 7: return "7";
case 8: return "8";
case 9: return "9";
case 10: return "10";
case 11: return "Jack";
case 12: return "Queen";
case 13: return "King";
default: return null;
}

您可以改为声明一个数组:

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

然后:

if (rank < 1 || rank > 13) return null;
return ranks[rank - 1]; // arrays are zero-based

关于java - 只是另一个新手 Java 编码器请求批准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5051783/

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