2017-03-01 58 views
0

我正在尝试编写一个程序来创建两个对象/类的实例(Dice)来模拟一对骰子。程序应该模拟2个骰子的滚动并使用OutputDice方法显示它们的值。在Java中使用set和get方法的骰子滚动程序

字段包含骰子的值。 SetValue方法将值存储在值字段中。GetValue方法返回骰子的值。方法Roll方法产生一个在1到6范围内随机数的骰子值。 OutputDice方法将骰子的值作为文本输出。

我意识到下面的代码是非常不完整的,但我不知道如何将随机函数封装到输出中。

我的两个班分别为:

import java.util.Random; 

public class Dice { 

    private int Value; 

    public void setValue(int diceValue) { 
      Value = diceValue; 
    } 

    public int getValue() { 
      return Value; 
    } 

    public void roll() { 
     //I am not sure how to structure this section 
    } 
} 

import java.util.Random; 
import java.util.Scanner; 

public class DiceRollOutput { 

    public static void main(String[]args) { 
     String firstDie; 
     String secondDie; 
     int firstNumber; 
     int secondNumber; 

     Scanner diceRoll = new Scanner(System.in); 

     Random Value = new Random(); 

     firstNumber = Value.nextInt(6)+1; 
     secondNumber = Value.nextInt(6)+1; 
    } 
} 
+0

请详细描述您的课程以及具体问题。 – betontalpfa

+0

//我不确定如何构建本节。为了生成随机骰子值,你可以在java – Abhishekkumar

回答

1

产生的骰子类,而不是主要方法随机整数。

import java.lang.Math; 
import java.util.Random; 
import java.util.Scanner; 

public class Dice { 

    private int value; 

    public void setValue(int diceValue) { 
      value = diceValue; 
    } 

    public int getValue() { 
      return value; 
    } 

    public void roll() { 
     //I am not sure how to structure this section 
     Random rand = new Random(); 
     value = rand.nextInt(6) + 1; 
    } 
} 

public class DiceRollOutput { 

    public static void main(String[]args) { 

     Dice firstDie = new Dice(); 
     Dice secondDie = new Dice(); 

     firstDie.roll(); 
     secondDie.roll(); 


     System.out.println("Dice 1: "+ firstDie.getValue()); 
     System.out.println("Dice 2: "+ secondDie.getValue()); 
    } 
} 
+0

@ Thanks uzr中使用随机类,让我走上正轨,并解决了我问的问题! – BWMustang13