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

标签 java eclipse

所以我试图创建的程序是掷骰子游戏,我想看看该程序是否在重复,因为我真的不知道如何使用递归方法,而教授又复习了一会儿前。我想看看它是否运行正常,但是当我运行这个时,我 获取:“线程“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/

相关文章:

java - 从 ajax 请求访问 javax servlet

java - jackson Xml : How to add namespace only on root?

java - 未在包含 JTable 的 JScrollPane 中调用 TableModel

java - TimePickerDialog 和时区

java - 扩展接口(interface)上的方法

Windows 8 上的 Eclipse 兼容性

eclipse 版本需要特定的 Apache Tomcat 服务器

java - setOnClickListener 从未触发 - Android/Eclipse

java - 如何在静态方法中使用 "runOnUiThread(runnable)"?

android - 如何在 Eclipse 中获取 Javax.servlet.* 类?