java - 从另一个类获取数据

标签 java class

我正在构建一个应用程序,并且正在尝试找到一种将数据从一个类获取到另一个类的方法。

在我的主类Driver中,我有一个抛出两个骰子的函数,然后我得到它们的总和。该函数是在名为 Dices 的类中创建的。 我有一个名为 Players 的新类,我需要从主类的骰子 throw 中获取数据。

代码如下

public class Player {
public String spillernavn;
public int pos;



public String SpillerNavn() {
        return spillernavn;
    }
public int move(int steps){
  move=??;
  pos=steps+pos;
    return ??;
}
public int SpillerPos() {
        return pos;
    }
}

方法 public int move(int steps){} 是我需要使用骰子抛出的数据,然后与 pos(代表位置)进行加法的地方。

主要功能如下

public static void main(String[] args) {

        //Intializing dices
        Dice die1 = new Dice();
        Dice die2 = new Dice();

        //Summ of dice
        int sum = die1.throwDice() + die2.throwDice();

最佳答案

文件名:Dice.java

import java.util.Random; 



public class Dice {

    private Random random;

    public Dice() {

        random = new Random();
    }  

    public int throwDice() {

        int num = 0;

        while(num == 0)  // Dice doesn't have a zero, so keep looping unless dice has a zero.
            num = random.nextInt(7);  // returns a random number between 0 - 6

        return num;
    }
}  

文件名:Players.java

public class Players {

    private int sum;


    public Players(int sum) {

        this.sum = sum;  // You got the data from `Driver class` here.
        // You got the sum of two dice. Now do whatever you want to.
    }
}  

public class Driver {

    public static void main(String[] args) {

        Dice dye1 = new Dice();
        Dice dye2 = new Dice(); 
        int sum = dye1.throwDice() + dye2.throwDice();
        Players player = new Player(sum);  // Passing the data to Class Players
    }    
}  

要发送数据,需要在()中传递参数

关于java - 从另一个类获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26564144/

相关文章:

java - 如何将POST中的json转换为javaBean

java - JPA CriteriaBuilder - 如何将具有不同动态类型的参数添加到标准?出现不明确的调用错误

java - 如何让用户可以选择我的 JList?

c++ - 使用默认和复制 ctors 进行初始化是否完全等效?

Java Action 监听器action在不同的类中执行

javascript - 如何仅在特定页面中删除页脚组件?

java - 根据附加值获取枚举?

java - Spring Data JPA - 保存重复的复合键时不会出现任何错误

c++ - 自定义类错误: incomplete type and can't be defined

用于 eclipse 的 PHP UML 类图插件?