【问题标题】:Get String from classes node cannot find symbol从类节点获取字符串找不到符号
【发布时间】:2016-01-20 13:21:19
【问题描述】:

我试图从类 String 的节点中获取,但编译器找不到变量。非常感谢您的帮助。

学生班:

public class Students {

    private int[] marks;
    private String name;

    public Students(String name, int[] marks) {
        this.name = name;
        marks = new int[5];
        for (int i = 0; i < marks.length; i++) {
            this.marks[i] = marks[i];
        }
    }
    public int getMarksI(int i) {
        return marks[0];
    }
    public int[] getMarks() {
        return marks;
    }
    public String getName() {
        return name;
    }
}

问题所在的函数:

public double AverageByName(Node < Students > s, String name) {
    Node < Students > p = s;
    while (p != null) {
        if (name == p.getName()) // this is the problem "cannot find symbol p.getName"
        {
            //
        }
        p.setNext();
    }
    return false;
}

除此之外还有一个Node类和Student类的链表在main中创建没有问题。

【问题讨论】:

  • 尽管您有实际问题,但您应该看看how do i compare strings in java
  • 查看p 的类型——它是Node&lt;Student&gt;,而不是Student。现在您还没有向我们展示Node 类,但大概它没有getName() 方法...

标签: java class nodes symbols


【解决方案1】:

如果 Node 使用 getValue() 公开其 Student 值,它将是:

if (name.equals(p.getValue().getName())) 

【讨论】:

  • 非常感谢您的帮助!
【解决方案2】:

应该是这样的

public double AverageByName(Node < Students > s, String name) {
Node < Students > p = s;
while (p != null) {
    if (name.equals(p.getValue().getName())) // you need to get the Student object from the node first
    {
        //
    }
    p.setNext();
}
return false;

}

或者可以转换成

Student std = (Student)p.getValue();

我不知道你关于 Node 类的问题。最好也共享 Node 类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    • 2021-04-09
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 2013-12-09
    • 1970-01-01
    相关资源
    最近更新 更多