我是java编码的新手,很抱歉初学者的问题。我很确定我忽略了一些简单但我无法在之前的主题中找到解决方案。
我正在尝试构建一个对象“computerDraw”。当我创建一个新的“computerDraw”时,我希望计算机决定他是否从int数组中提取1,2或3个数字。这些数字是随机抽出的。
绘制的数字应存储在变量“computerSumCards”中。
我创建了一个getter来返回computerSumCards,但每次都返回“0”。
我无法弄清楚为什么会这样。谢谢你的帮助!
public class computerDraw {
int computerSumCards;
int getAmountOfComputerCards;
int randomCard;
int draws = 0;
private int[] possibleDraws = {1, 2, 3};
int computerCanDraw = (possibleDraws[new Random().nextInt(possibleDraws.length)]);
public void drawLoop() {
while (draws < computerCanDraw) {
int[] cards = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10};
randomCard = (cards[new Random().nextInt(cards.length)]);
computerSumCards += randomCard;
}
}
public int getComputerSumCards() {
return computerSumCards;
}
public int getAmountOfComputerCards() {
getAmountOfComputerCards = draws;
return getAmountOfComputerCards;
}
}
答案 0 :(得分:2)
您不会在任何地方更改draws
值,此时getAmountOfComputerCards = draws;
总是指定为0. {/ p>
在computerSumCards += randomCard;
添加draws++;
之后,应该没问题。没有它,你将获得无限循环。
答案 1 :(得分:1)
该类不会“忽略”while
循环。循环位于方法drawLoop()
内。如果你想让它运行,你需要明确地调用它
computerDraw draw = new computerDraw();
draw.drawLoop();
作为旁注,课程名称后来以资本开头。 computerDraw
应为ComputerDraw
。
答案 2 :(得分:0)
我还是新手,但试试这个:
public int drawLoop() {
while (draws < computerCanDraw) {
int[] cards = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10};
randomCard = (cards[new Random().nextInt(cards.length)]);
computerSumCards += randomCard;
}
return computerSumCards;
}
public int getComputerSumCards() {
return drawLoop();
}
答案 3 :(得分:0)
你需要调用draw.drawLoop();但即使你调用你的while循环也会进入无限循环。 draw和computerCanDraw的值永远不会得到更改,并且绘图始终保持&lt; computerCanDraw值。您应该更改绘制值或正确实现computerCanDraw。