简体   繁体   English

Java中的骰子游戏(从带有构造函数的类中调用)

[英]dice game in java (calling from a class with a constructor)

I'm trying to make a dice game with a dice that can give a random number between 1 to 6. I have a class that is called Die which consist of one constructor and two methods. 我正在尝试制作一个骰子游戏,该骰子可以给出1到6之间的一个随机数。我有一个叫做Die的类,它包含一个构造函数和两个方法。 The constructors main purpose is to initiate a random value and the two methods should roll the dice and return the value respectively. 构造函数的主要目的是初始化一个随机值,这两个方法应掷骰子并分别返回该值。 My problem is that I don't know how to roll the dice and retrieve the number after I have made an object. 我的问题是,我制作对象后不知道如何掷骰子并检索数字。

import java.util.Random;

class Die{
    int dots,roll;
    Random number = new Random();

    public Die(){
        int dots = number.nextInt(6)+1 ;
    }

    public void roll(){
        roll = number.nextInt(dots)+1;
    }

    public int getDots(){
        return roll;
    }

}

public class Uppg1 {
    public static void main (String args[]){
        Die die = new Die();
        System.out.println("Du fick "+die.getDots());

    }
}

It appears that my code goes to the constructor and not to methods. 看来我的代码去了构造函数而不是方法。 I want the value from the constructor and then roll the dice and then get the value from method getDots. 我要从构造函数中获取值,然后掷骰子,然后从方法getDots中获取值。

Inside Die constructor you update internal dots variable instead of class member. Die构造函数中,您更新内部dots变量而不是类成员。 Use: 采用:

public Die(){
    dots = number.nextInt(6)+1 ;
}
  int dots = number.nextInt(6)+1 ;

This is different variable from the variable 这与变量不同

class Die{
    int dots,roll;

so make it 所以做到

dots = number.nextInt(6)+1 ;

so that you will get the right value. 这样您将获得正确的价值。

I have modified the code for you just take a look:import java.util.Random; 我已经为您修改了代码,看看:import java.util.Random;

class Die{
    int dots,roll;
    Random number = new Random();

    public Die(){
         dots = number.nextInt(6)+1 ;
    }

    public void roll(){
        roll = number.nextInt(dots)+1;
    }

    public int getDots(){

        return roll;
    }

}

public class Uppg1 {
    public static void main (String args[]){
        Die die = new Die();
        die.roll();
        System.out.println("Du fick" +die.getDots());

    }
}

remove int from Die constructor as it already defined as global, your prog. 从Die构造函数中删除int,因为它已经定义为全局编,您的编。 doesn't call roll method anywhere hence need to call that. 不会在任何地方调用roll方法,因此需要调用该方法。

int dots = number.nextInt(6)+1 does not change the field dots but creates a new variable dots int dots = number.nextInt(6)+1不会更改字段dots但会创建一个新的可变dots

Additionally you never call roll() so roll=null and getDots() returns null. 另外,您永远不会调用roll()所以roll=null并且getDots()返回null。

You can roll the dice by calling die.roll() in the Uppg1 main method. 您可以通过在Uppg1 main方法中调用die.roll()来掷骰子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM