【发布时间】:2016-02-26 23:18:43
【问题描述】:
所以我在玫瑰游戏中构建花瓣并将骰子定义为 dice1、dice 2 等。然后我运行一个循环来确定每个骰子的值是多少,并将其添加到游戏值中。我想要的是循环的每个序列都可以切换它正在查看的变量。所以首先运行看看 dice1。然后再看 dice2。
public class Rosegame
{
private int dice1;
private int dice2;
private int dice3;
private int dice4;
private int dice5;
private int gameValue;
public void rollDice()
{
dice1 = (int) ((6-1+1) * Math.random()) + 1;
dice2 = (int) ((6-1+1) * Math.random()) + 1;
dice3 = (int) ((6-1+1) * Math.random()) + 1;
dice4 = (int) ((6-1+1) * Math.random()) + 1;
dice5 = (int) ((6-1+1) * Math.random()) + 1;
}
public void printValues()
{
System.out.println("Dice 1 is:" + dice1);
System.out.println("Dice 2 is:" + dice2);
System.out.println("Dice 3 is:" + dice3);
System.out.println("Dice 4 is:" + dice4);
System.out.println("Dice 5 is:" + dice5);
}
public int calculatePetalsOnRose()
{
gameValue = 0;
for(int i = 1; i <=5; i++)
{
if (dice1 == 5)
{
gameValue = gameValue + 4;
}
else if (dice1 == 3)
{
gameValue = gameValue + 2;
}
else
{
gameValue = gameValue;
}
}
return gameValue;
}
}
这是我当前的代码,我需要的是在它有 dice1 的 if 语句中,我希望它能够在每次循环时更改。他们也是一个运行方法并允许输入的驱动程序,但到目前为止它正在工作。提前非常感谢您
编辑:
将变量切换到我现在拥有的数组,这给了我一个错误,说 java.lang.NullPointerException。它发生在调用 rollDice 函数时。
public class PetalsGame
{
private int[] anArrayDice;
private int gameValue;
public void rollDice()
{
anArrayDice[0] = (int) ((6-1+1) * Math.random()) + 1;
anArrayDice[1] = (int) ((6-1+1) * Math.random()) + 1;
anArrayDice[2] = (int) ((6-1+1) * Math.random()) + 1;
anArrayDice[3] = (int) ((6-1+1) * Math.random()) + 1;
anArrayDice[4] = (int) ((6-1+1) * Math.random()) + 1;
}
public void printDice()
{
System.out.println("Dice 1 is:" + anArrayDice[0]);
System.out.println("Dice 2 is:" + anArrayDice[1]);
System.out.println("Dice 3 is:" + anArrayDice[2]);
System.out.println("Dice 4 is:" + anArrayDice[3]);
System.out.println("Dice 5 is:" + anArrayDice[4]);
}
public int calculateAllPetals()
{
gameValue = 0;
for(int i = 0; i <=4; i++)
{
if (anArrayDice[i] == 5)
{
gameValue = gameValue + 4;
}
else if (anArrayDice[i] == 3)
{
gameValue = gameValue + 2;
}
else
{
gameValue = gameValue;
}
}
return gameValue;
}
}
我可以通过添加 anArrayDice = new int[5]; 来修复它在 rollDice 方法内部。谢谢你的帮助。
【问题讨论】:
-
我将变量切换到私有 int[] 骰子;然后使用相同的 math.random 定义骰子值。我有线 dice[0] = (int) ((6-1+1) * Math.random()) + 1;在运行时给我一个错误。在底部的 bluej 终端中显示 java.lang.nullpointerexception。我对数组不了解的地方?
-
您能否更新您的问题,以便清楚您尝试了什么?
标签: java