我正在构建一个应用程序,并且正在尝试找到一种将数据从一个类获取到另一个类的方法。
在我的主类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/