【发布时间】:2018-09-09 11:41:12
【问题描述】:
在完成大富翁类型的基于文本的游戏时,我在 Java 中将变量数据从类传输到类时遇到了一些问题。
我一直在尝试将 roll1 和 roll2 变量从 Dice 类传输到 Board 类,但由于某种原因,数据没有正确传输,当我从 2 Rollin Board 类返回组合数据时,它只是返回为 0。
这是我的课程:
public class Dice {
static int dots, roll1, roll2, flag;
Random number = new Random();
public Dice(){
dots = number.nextInt(6)+1 ;
}
public void roll1(){
roll1 = number.nextInt(dots)+1;
}
public void roll2(){
roll2 = number.nextInt(dots)+1;
}
public int getDots1(){
return roll1;
}
public int getDots2(){
return roll2;
}
public String getSame(){
if(roll1 == roll2){
flag++;
return("Your rolls were the same");
}
else{
return(" ");
}
}
}
public class Board {
static int roll1 = Dice.roll1;
static int roll2 = Dice.roll2;
public static int i;
public int Turn = 0;
public int totalP = 0;
public static int Pos = 0;
public static int[] Players= {1, 2, 3, 4};
public static int[] Square = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25};
public static int Money = 40000;
static ArrayList<Integer> pPos = new ArrayList<Integer>();
void pPosList(){}
public Board(int totalP){
this.totalP = totalP;
}
public static int getPos(){
while(Money != 0){
for(i=0;i<Players.length;i++){
System.out.println("Player Turn: Player "+(i));
Pos = Square[roll1 + roll2];
pPos.set(0, Pos);
return roll1;
}
}
}
}
public class Blobfish {
public void main(String[] args) {
System.out.println(" " +Board.getPos());
Dice dice = new Dice();
dice.roll1();
dice.roll2();
System.out.println("First Roll: " +dice.getDots1());
System.out.println("Second Roll: " +dice.getDots2());
System.out.println("" + dice.getSame());
System.out.println("Your Current Position = " +Board.getPos());
}
}
【问题讨论】:
-
首先这些不应该是静态的。您有一个 Board 实例,并且有一对 Dice。你为什么要让这些静态的?将它们与实例相关联。您不希望世界上所有的棋盘或世界上的所有骰子都具有相同的值吗?
-
如何将值从一个类传递到另一个类?
-
您在代码中的哪个位置传递值?无处 ;) 板中的 roll1 与骰子中的 roll1 不同(即使它们是静态的并且它们被称为相同 - 它们与您声明它们的类相关)。您应该执行类似 board.roll1=dice.roll1 的操作。卷后。这个静态 int roll1 = Dice.roll1;不会终生连接它们
-
变量是静态的,因为每当我将它们设为非静态时,主函数将无法正常运行。
-
那么我到底需要做什么才能让Dice中的roll1和roll2转移到Board中的roll1和roll2,这样我就可以计算出用户的当前位置了?
标签: java class variables inheritance