无法从 class/ 调用方法

Trouble calling methods from a class/

谁能告诉我这些代码有什么问题吗?

public class Student {
    String name;
    int roll_no;
    public void getDetails(String Name, int roll) {
        name = Name;
        roll_no = roll;
    }
}

还有这个

public class StudentRun {
    Student student = new Student();
    String n = "John";
    int r = 2;
    student.getDetails(n, r);
}

显示错误:

Multiple markers at this line

在我调用 student.getDetails(n,r)

的线路上

在我看来,您正在调用该方法,但未将其包装在 class StudentRun 中的方法中。尝试使用构造函数或其他方法调用 student.GetDetails

喜欢 void callStudentRun {

student.Getdetails();

}

您不能在 class 中调用方法,除非它被包装在方法中。

您的 Student class 还缺少 构造函数 (实例化 class 时调用的方法)并且缺少属性可见性的上下文( public/protected/private)。 构造函数必须将自身称为 class,在您的情况下:

public class Student {
 protected String name;
 protected int roll_no;
 public Student(String Name, int roll) {
    this.name = Name;
    this.roll_no = roll;
 }

 public String getName() {
  return this.name
 } 
 ....
}

正确构建 class 后,您需要执行以下操作来实例化它:

class OtherClass {
 public static void main (String[] args) {
 student = new Student("John", 42);
 System.out.println(student.getName());  
 }
}