gpt4 book ai didi

java - 为什么我的程序无法运行?

转载 作者:行者123 更新时间:2023-11-30 06:14:57 25 4
gpt4 key购买 nike

所以我试图创建的程序是掷骰子游戏,我想看看该程序是否在重复,因为我真的不知道如何使用递归方法,而教授又复习了一会儿前。我想看看它是否运行正常,但是当我运行这个时,我获取:“线程“main”中的异常 java.lang.StackOverflowError at java.util.Random.(Unknown Source) at Main.rollDice(Main.java:25) at Main.rollDice(Main.java:29) 和 Main .java:29 重复了很多次。我是编码新手,而且我的教授不是最好的。请帮忙,此任务将在 12 小时内到期!

import java.util.*;

public class Main {
static int die1 = 0, die2 = 0, dieSum = 0, balance = 0, bet = 0;
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
Random gen = new Random();

System.out.println("Welcome to the game of Craps!");
System.out.println("Every round you will make a wager with dollars only.");
System.out.println("The minimum wager is $10.");
System.out.println("You can continue to play as long as you have enough money to cover the minimu wager.");
System.out.println("You can cash out at the end of any round if you would like.");

balance = gen.nextInt(1000)+50;
System.out.println("Your starting balance is: $" + balance);
int i = 0;
if ((rollDice()<=2)||(i==5)) {
System.out.println(rollDice());
i = i++;
}
}
public static int rollDice() {
Random gen = new Random();
die1 = gen.nextInt(6)+1;
die2 = gen.nextInt(6)+1;
dieSum = die1 + die2;
return rollDice();
}
// TODO Auto-generated method stub

}

最佳答案

您的 rollDice 方法无条件地递归调用自身。此行返回调用 rollDice return rollDice(); 的结果。每个递归调用都会添加到执行堆栈中。一旦堆栈“空间不足”,就会抛出堆栈溢出异常。我怀疑你打算像这样返回 dieSum

public static int rollDice() {
Random gen = new Random();
die1 = gen.nextInt(6)+1;
die2 = gen.nextInt(6)+1;
dieSum = die1 + die2;
return dieSum;
}

关于java - 为什么我的程序无法运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49433619/

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