我正在构建一个应用程序,我正在尝试找到一种方法将数据从一个类传递到另一个类。
在我的主类叫做 Driver ,我有一个函数会抛出两个骰子,然后我得到它们的总和。此功能在名为 Dices 的类中创建。 我有一个名为 Players 的新类,我需要从我的主类中获取掷骰子的数据。
代码如下
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;
}
}
Methode 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();
答案 0 :(得分:1)
你可以这样做。
public class Player {
public String spillernavn;
public int pos;
public String SpillerNavn() {
return spillernavn;
}
public int move(int steps, int move){
move=move;
pos=steps+pos;
return ??;
}
public int SpillerPos() {
return 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();
player.move(steps, move);
供将来参考。你应该在你的玩家类中创建一个骰子的实例。它简单地在类之间传递数据。吸气者和二传手。
答案 1 :(得分:1)
文件名: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
}
}
要发送数据,您需要传递()