java - 在方法之间传递变量的问题

标签 java methods

我正在创建一个具有不同方法的骰子游戏。但是,我似乎无法弄清楚如何在我的方法之间传递变量以在其他方法中使用。它从一个菜单开始,用户可以在其中“选择”1(奇数)或 2(偶数),然后进入掷骰子方法以获取掷骰子的总和,然后使用计算方法来告诉用户他们是赢了还是输了。但是,我似乎无法弄清楚如何传递 diceSum 并在计算方法中使用的方法之间进行选择。

我似乎无法弄清楚如何在 diceCalc() 中使用 select 和 diceSum 来为用户打印答案。

private static void guess(){
    Scanner input = new Scanner(System.in);
    System.out.print("(1) Odd\n"
            +"(2) Even\n"
            +"(3) Quit Game\n"
            +"What is your selection: ");
    try {
        int select = input.nextInt();
        if(select == 1) {
            System.out.println("");
            diceRoll();
        } else if(select == 2) {
            System.out.println("");
            diceRoll();
        } else if(select == 3) {
            System.out.println("Thank you for playing Dueling Dice v1.0...");
    system.out(0);
}

private static void diceRoll() {
    int roll1, roll2, diceSum;
    roll1 = (int)(Math.random()*6+1);
    roll2 = (int)(Math.random()*6+1);
    diceSum = roll1 + roll2;

    System.out.println("    Dice 1 roll = " + roll1);
    System.out.println("    Dice 2 roll = " + roll2);
    System.out.println("TOTAL dice roll = " + diceSum);
    diceCalc(); // this is called in the main  after the guess since guess performs the roll 
}

private static void diceCalc() {
    if (diceSum % 2 != 0 && select == 1 || diceSum % 2 == 0 && select == 2) {
        if (select == 1) {
            System.out.println("Dice rolled = " + diceSum + "and you selected odd");
        } else {
            System.out.println("Dice rolled = " + diceSum + "and you selected even");
        }
        System.out.println("CONGRATULATIONS! You WIN!!");
        won++;
        played++;
    }else if (diceSum % 2 == 0 && select == 1 || diceSum % 2 != 0 && select == 2){
        if (select == 1) {
            System.out.println("Dice rolled = " + diceSum + "and you selected odd");
        } else {
            System.out.println("Dice rolled = " + diceSum + "and you selected even");
        }
        System.out.println("I am sorry you lost!");
        lost++;
        played++;
    }
    System.out.print("it is making it here!");

最佳答案

您可以将 diceSum 传递给 diceCalc 方法。

diceCalc(diceSum);  // this is called in the main  after the guess since guess performs the roll 

然后将参数添加到diceCalc函数中。

private static void diceCalc(int diceSum)

关于java - 在方法之间传递变量的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44206587/

相关文章:

java - 使用 mariadb 驱动程序时未找到 JDBC、Socket 工厂

java - 使用Uploadify时出错

java - 声明接口(interface)方法仅允许实现的类

java - 创建构造函数、方法和存储数组的规范令人困惑?

Java:从 JAR 文件中的类文件中获取方法 stub 的简单方法?反射?

java - C++ 等价于 java 的 instanceof

java - 如何在 GWT 客户端中获取本地主机服务器的响应?

java - 如何使用 AlertDialog.Builder onItemClickListener 创建 ListView?

python - 我如何打破2个循环? (Python)

java - 接收和返回方法