gpt4 book ai didi

java - 带有用户输入的标记变量以退出

转载 作者:行者123 更新时间:2023-12-02 09:11:38 25 4
gpt4 key购买 nike

我有一个程序应该用java模拟扑克游戏。我有一个名为 Poker 的方法类和一个名为 CheckPoker 的支票类,它调用方法类中的方法。我什至无法检查算法部分是否有效,因为在询问用户是否愿意更换任何卡时。循环应在输入 5 张卡后退出,或者如果用户输入“1”,但在运行程序时,for 循环不会退出,直到输入 5 张卡值,然后抛出“java.lang.ArrayIndexOutOfBoundsException:Index” -1 超出长度 56"错误。我尝试过 for 循环、while 循环、do-while 循环,但到目前为止似乎都不起作用。

import java.util.*;

public class Poker {
private String[] deck = {
"D1","D2","D3","D4","D5","D6","D7","D8","D9","D10","DJ","DQ","DK","DA",
"C1","C2","C3","C4","C5","C6","C7","C8","C9","C10","CJ", "CQ","CK","CA",
"H1","H2","H3","H4","H5","H6","H7","H8","H9","H10","HJ", "HQ","HK","HA",
"S1","S2","S3","S4","S5","S6","S7","S8","S9","S10","SJ", "SQ","SK","SA"};
private List<String> hand = new ArrayList<>();
public Poker(){
Collections.shuffle(Arrays.asList(deck));
}

public void playGame(){
System.out.print("The first five cards are: ");
for(int i = 0; i<5; i++){
System.out.print(deck[i] +", ");
}
System.out.println(" ");
int k = 0;
String j;
List<String> discard = new ArrayList<>();
Scanner in = new Scanner(System.in);
System.out.println("Enter up to 5 cards you want to get rid of (1 to quit): ");
while (k<5) { //this is the loop I'm having trouble with
j = in.next();
if(!j.equals("1")){
j = in.next();
discard.add(j);
k++;
}else{
break;
}
}
List deckList = Arrays.asList(deck);
String[] discard1 = discard.toArray(new String[0]);
for(int l = 0; l<k; l++){
int m = deckList.indexOf(discard1[l]);
String n = deck[m];
deck[m] = deck[l+5];
deck[l+5] = n;
}
System.out.print("Your new hand is: ");
for(int i = 0; i<5; i++){
System.out.print(deck[i] +", ");
hand.add(deck[i]);
}
System.out.println(" ");
}

最佳答案

尝试下面的代码。看来您每次迭代都抓取了两张卡,并且没有将它们全部捕获到 ArrayList 中。

Scanner in = new Scanner(System.in);
System.out.println("Enter up to 5 cards you want to get rid of (1 to quit): ");
while (k<5) { //this is the loop I'm having trouble with
j = in.nextLine();
if(j.equals("1") {
break;
}
discard.add(j);
k++;
}

关于java - 带有用户输入的标记变量以退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59364722/

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