0
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]);
        }
    }

プログラムの前半で、別のクラスに従って格納するように配列を設定しotherClassint numStudents最初は 0 に設定します。firstName と lastName を収集した後、配列をアルファベット順に並べて、各人の生徒数を調べます。セッターを使用して、配列に格納されているsetnumStudentsものを変更しようとします。numStudents私のコードをそのまま使用すると、次のエラーが発生します。

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

この問題について助けてくれてありがとう

4

2 に答える 2

1

私はあなたが欲しいと思います:

listOfName[i].setnumStudents(val);

またはその線に沿った何か。Java コーディング規約では、通常、大文字で始まるキャメル ケースのクラス名が使用されます。otherClassクラス名ですか?OtherClass混乱を避けるべきです。

「listOfTutor[i]」の正しいインスタンスかどうかはわかりませんが、のインスタンスlistofName[i]見つける必要がありますotherClass

于 2013-03-26T16:43:26.947 に答える
0

非静的メソッド setnumStudents(int) は静的コンテキストから参照できません

インスタンス(オブジェクト)を使用することになっているのに、クラスを使用して非静的メソッドにアクセスしていることを意味します。

以下では

otherClass.setnumStudents(val);

otherClass は、言及している他のクラスの名前ですか? その場合、このクラスをインスタンス化し、インスタンスを使用する必要があります。

ところで、Java のクラス名は通常、慣例により大文字で始まります。

于 2013-03-26T16:41:11.500 に答える