在 java 中的 2 个单独的 类 中使用数组

Using arrays in 2 separate classes in java

我如何在另一个 class 中使用主数组中的数组。我正在制作一个游戏,我需要进行三次单次掷骰。然后我获取每个值并进行比较,比如 2/3 数字是否匹配。如果然后加到 12,则将底池还给玩家。 这是 class 我想使用数组信息的地方。我昨晚学习了数组和循环,所以我真的不知道我在做什么

    import java.util.Scanner;

public class Game {

private double Bet;
private double Pot;
private double TotalPot;

public void Pot( ){
Pot = 50;
}
public void inputBet( ) {
    Scanner keyboard = new Scanner (System.in);
    System.out.println("Please enter the current month in numerical format: ");
    Bet = keyboard.nextDouble();
    if (Bet <= Pot) {
        System.out.println("Error, Bet out of range");

        inputBet();
    }
    else if (Bet == 0) {
        System.out.println("Thank you for playing");
    }
}

public void inputEnd( ){

}

public void removeBet( ){
    TotalPot = Bet - Pot;
}
public void dieComparison1(){
if ((die[0] == die[1]) || (die[0] == die[2])){
    TotalPot = (Bet * 2) + Pot;
    }
}
public void print(){
System.out.println(+ TotalPot);}
}

这是我创建数组的主要位置。

public class Assign3 {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    //Game smith = new Game();
    //smith.Pot();
    //smith.inputBet();
    int[] die = new int[3];
     Die bob = new Die();
     int total = 0;
     for(int i = 0; i < 3; i++){
        die[i] = bob.rollDie();
        bob.displayDie(die[i]);
        total = total + die[i];
     }
     bob.displayDie(total);


}
}

在上面的代码中,您已经在 main 方法中发布了您已经注释掉了您创建 Game class:

实例的行
//Game smith = new Game();
//smith.Pot();
//smith.inputBet();

因为您首先创建了 Game 的实例并将其存储在变量 smith 中,然后您在 [=17] 上调用了方法 PotinputBet 方法=] 变量,你可以在 Game class 中声明另一个方法,比如 rollDie 来包含你拥有的用于掷骰子的代码,并将其称为 smith.rollDie() 来自你的 main 方法。这将消除从 Game class.

访问您在 main 中创建的数组 die 的要求

以上我想表达的意思是:

  1. 首先,您在 Game class 中创建一个类型为 int[] 的变量 die,并将其初始化为三个大小:

    private int[] die = new int[3];
    
  2. 你创建一个方法说 rollDie() 方法包含滚动骰子的方法:

    public void rollDie(){
        Die bob = new Die();
        int total = 0;
        for(int i = 0; i < 3; i++){
            die[i] = bob.rollDie();
            bob.displayDie(die[i]);
            total = total + die[i];
        }
        bob.displayDie(total);
    }
    
  3. 现在在您的 main 方法中注释所有未注释的内容,取消注释所有已注释的内容。然后添加行 smith.rollDie() 来掷骰子并得到结果:

    Game smith = new Game();
    smith.Pot();
    smith.inputBet();
    smith.rollDie();
    // Here call the other method that are required to play the game like `dieComparision1()` etc.
    /*int[] die = new int[3];
    Die bob = new Die();
    int total = 0;
    for(int i = 0; i < 3; i++){
       die[i] = bob.rollDie();
       bob.displayDie(die[i]);
       total = total + die[i];
    }
    bob.displayDie(total);*/