三个骰子对象并抛出每个骰子。 投掷的结果应显示在输出窗口中。我正在从我之前的工作(PS。重复使用此代码折腾每个骰子)开始这项练习。我有两个类:App和Dice类。骰子类很好。
编辑: 这篇文章与另一篇文章相关联:m https://stackoverflow.com/questions/16878070/alternative-dice-toss-technique这个问题的不同之处在于分解我经过试验和测试过的代码[从前一篇文章同时投掷的3个骰子],一次三次掷骰子
类App如下 - 全套CLass应用代码 - 已更新
import javabook.*;
class App
{
public static void main(String args[])
{
App thisProgram = new App();
}
//outside a main class
public App()
{
//contsructor
//Dice aDice
//set variables
//int anDice = 0;
//int faceValue;
//Declare objects
Dice diceOne;
Dice diceTwo;
Dice diceThree;
int aNumber = 0;
int numThrown = 0;
//while(numThrown < 4) //UPDATED - commented out
//int afaceValue;
//declare objects
MainWindow mWindow;
//Dice aDice; //UPDATED - commented out
InputBox iBox;
OutputBox oBox;
//create objects
mWindow = new MainWindow();
//aDice = new Dice(); //UPDATED - commented out
iBox = new InputBox(mWindow);
oBox = new OutputBox(mWindow);
diceOne = new Dice();
diceTwo = new Dice();
diceThree = new Dice();
//Use objects
mWindow.show();
oBox.show();
while(numThrown < 3) //<4
{
Dice dice = new Dice();
aNumber = iBox.getInteger("Enter 1 to throw the dice, or 0 to exit: ");
if(aNumber == 1)
{
dice.throwDice();
int rollledNum = dice.getFaceValue();
oBox.println( "You threw : " + dice.getFaceValue() );
}
else
{
return;
}
numThrown++;
}
}
}
屏幕截图结果如下 使用上面的代码更新了下面的屏幕抓取:
类骰子如下这没关系。
class Dice
{
//public static void main(String args[])
//data
//private constants
final int NUMBER_OF_SIDES = 6;
//private variables
private int faceValue;
//constructors
public Dice()
{
this.faceValue = 0; //zero if not thrown.
}
//methods - behavious
public void throwDice()
{
this.faceValue = 1 + (int) (Math.random() * NUMBER_OF_SIDES);
}
//method - get (accessors) and sets (mutators)
public int getFaceValue()
{
return(this.faceValue);
}
}
答案 0 :(得分:2)
int aNumber = 0;
int numThrown = 0;
Dice dice = new Dice();
while(numThrown < 3)
{
aNumber = iBox.getInteger("Enter 1 to throw the dice, or 0 to exit: ");
if(aNumber == 1)
{
dice.throwDice();
int rollledNum = dice.getFaceValue();
oBox.println( "You threw : " + dice.getFaceValue() );
}
else
{
return;
}
numThrown++;
}
答案 1 :(得分:1)
这样你就可以一次掷一个骰子(如果你愿意的话,可以多掷三个骰子。)
Dice dice = new Dice(); // 1 dice for all rolls.
while(true){
aNumber = iBox.getInteger("Enter 1 to throw the dice, or 0 to exit: ");
if(aNumber == 0){
break; // bust out of the loop if user enters 0.
}
dice.throwDice();
oBox.println( "You threw : " + dice.getFaceValue() );
}