默认和参数化构造函数 [英] Default and parameterized constructor

查看:109
本文介绍了默认和参数化构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,伙计们

我希望您能帮助我完成我的计划。我还在学习java,对我来说感觉就像是一门外语。所以我希望你能帮助我。



我的问题是:

创建一个代表骰子的类。该类应该有一个属性:边数。你应该包含一个

默认构造函数,它将边设置为6.你还应该包含一个参数化的构造函数,它将数字

的边作为参数。包含一个公共滚动方法,该方法返回一个介于1和骰子所具有的边数之间的随机数。 6面模具的值可以在1到6之间.20面模具的值可以在1到20之间。

包括一个测试主体,用于证明您的课程正常工作。



到目前为止,我正在尝试创建一个默认构造函数但是失败了:(



包死;

Hello, guys
I hope you can help me with my program. i'm still learning java, and it feels like a foreign language to me. so i hope you will be kind enough to help me.

my question is:
Create a class that represents a die. The class should have a single attribute: the number of sides. You should include a
default constructor that sets the sides to 6. You should also include a parameterized constructor that takes the number
of sides as a parameter. Include a public roll method that returns a random number between 1 and the number of sides
that the die has. A 6 sided die can have values between 1 and 6. A 20 sided die can have values between 1 and 20.
Include a test main that demonstrates that your class works.

So far I am trying to create a default constructor but failed miserably :(

package die;

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


public class Die {
    private int NumberOfSides;
    public Die(){
        NumberOfSides=6;
    }
public int getNumberOfSides(){
    return NumberOfSides;
}
}
class dieRoll{
    public static void main(String[] args) {
        Die dieObject=new Die();
        System.out.println(dieObject.getNumberOfSides());

    }

推荐答案

你试过运行上面的程序,我觉得程序不会运行,下面是可执行代码:



have you tried running the above program, i don't think the program will run, below is the executable code:

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


class Die {
    private int NumberOfSides;
    public Die(){
        NumberOfSides=6;
    }
public int getNumberOfSides(){
    return NumberOfSides;
}
}
 public class dieRoll{
    public static void main(String[] args) {
        Die dieObject=new Die();
        System.out.println(dieObject.getNumberOfSides());

    }
}





使用dieRoll名称保存文件,编译并运行它。



但是,我看不到其中的roll方法,你可能应该使用roll方法和dieObject.rollmehtod,它将返回1到6之间的随机数。



问候,

panduranga。



Save the file with dieRoll name, compile it and run it.

But , i cannot see the roll method in it, you should probably right a roll method and and dieObject.rollmehtod which will return the random number between 1 to 6.

Regards,
panduranga.


这篇关于默认和参数化构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆