调用方法不起作用

时间:2013-03-21 18:32:31

标签: java methods

所以我得到了

public static void main(String[] args) {

    System.out.println("Trying to open lock"); 
    System.out.println("Trying ");
    ComboLock numbers = new ComboLock();
    int number1 = numbers.ComboLock;
    `

我试图从这个类中调用ComboLock

public class ComboLock {

private int number1, number2, number3;
private boolean locked;
public static final int SMALLEST_NUMBER = 1;
public static final int LARGEST_NUMBER = 39;

public ComboLock() {
    locked = true;
    Random rand = new Random();
    number1 = rand.nextInt(LARGEST_NUMBER - SMALLEST_NUMBER) + SMALLEST_NUMBER;
    number2 = rand.nextInt(LARGEST_NUMBER - SMALLEST_NUMBER) + SMALLEST_NUMBER;
    number3 = rand.nextInt(LARGEST_NUMBER - SMALLEST_NUMBER) + SMALLEST_NUMBER;
}

我正在尝试制作number1.ComboLock();说它找不到符号

5 个答案:

答案 0 :(得分:3)

public ComboLock() {

是构造函数,并且您正尝试将其作为

中的函数/方法来访问它
int number1 = numbers.ComboLock;

答案 1 :(得分:0)

当您调用ComboLock numbers = new ComboLock();时,它实际上调用您创建的ComboLock()函数。它被称为构造函数,它只适用于与类具有相同名称的函数。

答案 2 :(得分:0)

public ComboLock() {

是构造函数,是静态的,不能使用对象调用它。

答案 3 :(得分:0)

您正在尝试调用构造函数,而不是方法。作为一个构造函数,它不返回一个值,所以没有必要在某处分配它的返回值。

public class ComboLock {

    private int number1, number2, number3;
    private boolean locked;
    public static final int SMALLEST_NUMBER = 1;
    public static final int LARGEST_NUMBER = 39;

    public ComboLock() {
        locked = true;
        Random rand = new Random();
        number1 = rand.nextInt(LARGEST_NUMBER - SMALLEST_NUMBER) + SMALLEST_NUMBER;
        number2 = rand.nextInt(LARGEST_NUMBER - SMALLEST_NUMBER) + SMALLEST_NUMBER;
        number3 = rand.nextInt(LARGEST_NUMBER - SMALLEST_NUMBER) + SMALLEST_NUMBER;
    }
    public int getNumber1() {
        return number1;
    }
}

这样称呼:

ComboLock numbers = new ComboLock();
int number1 = numbers.getNumber1();

答案 4 :(得分:0)

我认为你打算这样做:

int number1 = numbers.number1;

...无论如何都无效,因为number1字段是私有的。