我正在处理涉及数组的赋值。今天到期了,我的教授还没有回到我身边,因为它是复活节,所以真的很感激。
我遇到的麻烦是2D阵列和打印。我已经检查了有关堆栈溢出的其他问题,这些问题是类似的,并试图将它们应用到我自己的但我仍然没有得到它。
我需要做的是将我的阵列,手,打印到控制台。我已经使用for循环以及增强for循环以外的循环,以试图让它工作但无济于事。
package pokerapp;
import java.util.Arrays;
import java.util.Scanner;
public class PokerApp {
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Welcome to the Poker App");
System.out.println();
//scanner
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
//create a deck
Deck myDeck = new Deck();
//shuffle cards
myDeck.shuffleCards();
String[][] hands = new String[4][5];
//deal cards
int i = 0;
for(int k=0;k<5;k++){
for(int j=0;j<4;j++){
hands[j][i] = myDeck.dealCard(i);
}
System.out.println("Hand " + hands + ": ");
}
//print 5 hands with one hand on each line
//four cards per hand
/* output should look something like this:
Hand 1: H4, C5, S7, H5
Hand 2: H3, C3, S10, S11
...
*/
//ask if user wants to continue
System.out.println("Would you like to continue? Y/N?");
choice = sc.nextLine();
System.out.println();
}
}
}
以下是我的甲板课程。
public class Deck {
private String[] suites = {"H","D","C","S"};
private String[] cards = new String[52];
public Deck() {
//create deck of cards
int index = 0;
//loop through the suite
for(String suite: suites){
//generate the ace through king
for(int j = 1; j<14;j++){
cards[index] = suite + j;
index++;
} //end of ace through king
}//end of suites
}//end of constructor
public void printCardArray(){
int index = 0;
for(String suite : suites){
for(int j =0; j<13;j++){
System.out.print(cards[index] + " ");
index++;
}
}
}//end of print card array
public void shuffleCards(){
//execute random number 100 times
for(int i=0;i<100;i++){
String savedCard = "";
int variant = ((int)(Math.random()*50)) + 1;
for (int j = 0; j < cards.length; j++){
if (j + variant < cards.length){
savedCard = cards[j];
cards[j] = cards[j + variant];
cards[j + variant] = savedCard;
}
}
}
}//end of shuffleCards
public String dealCard(int index){
return cards[index];
}
}
答案 0 :(得分:0)
我需要做的是将我的阵列,手,打印到控制台。
打印数组的方法有很多,它只取决于您希望如何显示输出。
你可以这样打印你的数组:
for (String[] array : hands) {
System.out.println(Arrays.toString(array));
}
或者这样:
for (String[] array : hands) {
for (String str : array) {
System.out.println(str);
}
}
另一种方式:
System.out.println(Arrays.deepToString(hands));
答案 1 :(得分:0)
取自原始代码
for(int k=0;k<5;k++){
System.out.print("Hand " + k + ": ");
for(int j=0;j<4;j++){
hands[j][k] = myDeck.dealCard(k);
System.out.print(hands[j][k]);
if(j != 3) {
System.out.print(", ");
}
}
System.out.println();
}
你可以
Hand 1: H4, C5, S7, H5
Hand 2: H3, C3, S10, S11
有了这个。但是,如果只有hands[j][k] = myDeck.dealCard(k);
返回H4, C5, S7, H5
答案 2 :(得分:0)
我建议你研究Arrays.deepToString()
Class Arrays