我正在尝试为执行以下操作的类编写代码:
询问要使用多少套牌
每次按下输入键时,程序将从卡座中产生一张未使用的卡
当没有更多的卡片可以发给时,程序会通知用户
程序允许用户再次播放
方法被广泛使用
到目前为止,我的代码如下所示:
import java.util.*;
public class IA3 {
@SuppressWarnings({ })
public static void play () {
}
@SuppressWarnings("resource")
public static void main(String[] args) {
boolean draw = true;
boolean pa = true;
Scanner console = new Scanner(System.in);
// TODO Auto-generated method stub
System.out.println("Hello! Please input the number of decks you would like to use:");
int decks = console.nextInt();
int t = decks * 52;
System.out.println("Your total amount of cards to use are " +t);
int a = 0;
do {
int[] deck = new int[t];
//declaration of suits and ranks
String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
//Initializing of the cards
for (int i = 0; i < t; i++) {
deck[i] = i;
}
System.out.println("Press enter to draw a random card : "); //allows player to prompt the system for the next card
String input = console.nextLine();
a++;
if (input.equals("")) {
// Shuffles the cards
for (int i = 0; i < 1; i++) {
int index = (int)(Math.random() * t);
int temp = deck[i];
deck[i] = deck[index];
deck[index] = temp;
}
for (int i = 0; i < 1; i++) {
String suit = suits[deck[i] / 13];
String rank = ranks[deck[i] % 13];
System.out.println(rank + " of " + suit);
}
if (a>t) {
System.out.println ("No more cards available");
break;
}
System.out.println("Draw another card? (Yes or No) : ");
String again = console.nextLine();
if (again.equals("Yes")) {
continue;
}
if (again.equals("No")) {
draw = false;
System.out.println("Game over!");
}
System.out.println("Play again? (Yes or No) : ");
String plag = console.nextLine();
if (plag.equals("Yes")) {
continue;
}
if (plag.equals("No")) {
pa = false;
System.out.println("Thank you for playing!");
break;
} while (pa == true);
}
} while (draw == true);
}
}
当我尝试运行1个以上的牌组时,会出现问题,有时会立即失败,而有时会运行4个交易然后失败。我似乎也无法使它再次运行。只要我输入“是”,它就会终止,而不是再次播放。如您所见,我那里没有方法(我在方法上迷失了方向)。任何帮助,将不胜感激,谢谢!
最佳答案
您应该发布完整的错误消息。没有它,很难猜测正在发生什么。我看到数组索引可能超出边界的至少一个地方:
String suit = suits[deck[i] / 13];
如果您的甲板多于1个,则此划分的结果将大于3。您可以使用以下方法修复它:
String suit = suits[(deck[i] / 13) % 4];
这样,您可以确保仅使用索引为[0,1,2,3]的元素。
关于java - 甲板交易Java,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24274919/