Java类变量赋值抛出错误

问题描述 投票:0回答:1

为什么我不能像这样定义左和右的下一个值?

public class Solution {
    Map<Integer, Node> map = new HashMap<>();
    public Node left = new Node(Integer.MIN_VALUE, null, null);
    public Node right = new Node(Integer.MAX_VALUE, null, null);
    left.next = right;
    right.prev = left;

    public static void main(String[] args) {
        System.out.println("");
    }
}

class Node {
    Node prev;
    Node next;
    int val;
    public Node(int val, Node prev, Node next) {
        this.val = val;
        this.prev = prev;
        this.next = next;
    }
}

当我编译它时,它会抛出:

Solution.java:14: error: <identifier> expected
    left.next = right;
             ^
Solution.java:15: error: <identifier> expected
    right.prev = left;
              ^

我尝试调试了一段时间,但没有成功。我已经定义了变量。而且错误信息也很模糊。

java class object variables attributes
1个回答
0
投票

遵循OOP的概念,如果你想设置你的

,请使用
Getter and Setter

left.next = right;
right.prev = left;
//Create getter and setter methods for your variables
class Node {
    Node prev;
    Node next;
    int val;
    public Node(int val, Node prev, Node next) {
        this.val = val;
        this.prev = prev;
        this.next = next;
    }
}

然后就可以设置了。

left.setNext(right);
right.setPrev(left);

希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.