This question already has answers here:
What is the reason behind “non-static method cannot be referenced from a static context”? [duplicate]

(13个回答)



“Non-static method cannot be referenced from a static context” error

(4个答案)


7年前关闭。





public class Thing
{
public static void main (String[] args)
    {
    //I set my veriables and prompt user to enter number of names
    //Prompt user for First and Last name and Store names in an array of classes

    Arrays.sort(listOfName, new Comparator<otherClass>()//Sort names according to last name
    //code here for that (which i have but not the issue)
    for (int i = 0; i<numName; i++)
        {
        ans = JOptionPane.showInputDialog(null,"How Many Students does: \n "+ listOfName[i]+ " Have");
        int val = Integer.parseInt(ans);
        otherClass.setnumStudents(val);// in my Separate class I have a setnumStudents
        }
    for(int i = 0; i<numName; i++)
        {
        System.out.println(listOfName[i]);
        }
    }


在程序的前面,我将数组设置为根据单独的类otherClass进行存储,并且在收集firstName和lastName之后,最初将int numStudents设置为0,然后按字母顺序排列该数组,然后查询每个人有多少学生。我使用setter setnumStudents尝试更改存储在数组中的numStudents。与我的代码一样,我得到此错误:

non-static method setnumStudents(int) cannot be referenced from a static context
        otherClass.setnumStudents(val);
             ^


感谢您在此问题上的任何帮助

最佳答案

我想你要:

listOfName[i].setnumStudents(val);


或类似的东西。 Java编码约定通常使用大写字母开头的驼峰式类名。 otherClass是类名吗?应该为OtherClass以避免混淆。

我不知道listofName[i]是否是'listOfTutor [i]'的正确实例,但是您需要找到otherClass的实例

关于java - 如何让我的二传手与单独的类(class)互动? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15642536/

10-08 21:59