所以我试图创建的程序是Craps的游戏,我试图看看程序是否重复,因为我真的不知道如何使用递归方法,教授过去了不久前。我想知道它是否正常运行,但是当我运行它时 得到:"线程中的异常" main" Main.rollDice(Main.java:29)Main.rollDice(Main.java:25)java.util.Random。(Unknown Source)的java.lang.StackOverflowError和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
}
答案 0 :(得分:1)
您的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;
}