0

所以我得到了

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(); 时遇到错误 说它找不到符号

4

5 回答 5

3
public ComboLock() {

是一个构造函数,并且您正尝试将其作为函数/方法访问

int number1 = numbers.ComboLock;
于 2013-03-21T18:34:20.553 回答
0

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

于 2013-03-21T18:34:46.637 回答
0
public ComboLock() {

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

于 2013-03-21T18:35:15.943 回答
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();
于 2013-03-21T18:35:23.420 回答
0

我认为您打算这样做:

int number1 = numbers.number1;

...这无论如何都行不通,因为该number1字段是私有的。

于 2013-03-21T18:35:53.593 回答