This question already has answers here:
Non-static variable cannot be referenced from a static context
                                
                                    (12个答案)
                                
                        
                                在8个月前关闭。
            
                    
我想找到x数量的宠物中输入的最小年龄。我曾尝试将'public static int youngestAge'放进去;但是,这只是让我为变量“ youngestAge”分配了最新的值。我认为这是因为关键字“ static”;因此,我尝试将其删除,但这只会导致netbeans告诉我“无法从静态上下文中引用非静态变量”。我希望代码能提供最低的输入年龄。

package pet;
import java.util.Scanner;
public class Pet
{
    public static String petName;
    public static int petAge, petWeight;
    public int youngestAge;


    public static String setPetName()
    {
       Scanner input = new Scanner(System.in);
       petName= input.next();
       return petName;
    }

    public int setPetAge()
    {
        Scanner input = new Scanner(System.in);
        petAge= input.nextInt();
        return petAge;
    }

    public int setPetWeight()
    {
        Scanner input = new Scanner(System.in);
        petWeight= input.nextInt();
        return petWeight;
    }


    public void getYoungestPet()
    {
        if (youngestAge<petAge)
            youngestAge=petAge;
        System.out.println("The youngest age is " + youngestAge);
    }
}

    package pet;
    import java.util.Scanner;
    public class PetMain extends Pet
    {

        public static void main(String[] args)
        {

        System.out.println("How many pets do you want to enter? " );
        Scanner data= new Scanner(System.in);

        int petNumber=data.nextInt();

        for (int i = 1;i<=petNumber; i++)
        {
        Pet PetObject = new Pet();

        System.out.println("Please enter name for Pet " + i );
        PetObject.setPetName();
        System.out.println("Your pet's name is : " + petName);
        System.out.println(" ");
        System.out.println("Please enter " + petName + "'s Age" );
        PetObject.setPetAge();
        System.out.println("Your pet's age is : " + petAge);
        System.out.println(" ");
        System.out.println("Please enter " + petName + "'s Weight" );
        PetObject.setPetWeight();
        System.out.println("Your pet's weight is : " + petWeight);
        System.out.println(" ");

        if (youngestAge<PetObject.petAge)
                youngestAge=PetObject.petAge;
        }
        System.out.println("The youngest age here is : " + youngestAge );
}

最佳答案

如果使用的if条件错误。它将检查当前Pet对象的年龄是否大于youngestAge,然后将youngestAge分配为当前Pet对象的年龄。

if (youngestAge<PetObject.petAge)
      youngestAge=PetObject.petAge;
}


这将产生最大年龄而不是最小年龄。

要获得最小年龄,仅当当前Pet对象的年龄小于youngestAge以获得最小年龄时,才需要分配youngestAge。

您得到的错误是因为您试图访问静态方法main中的Pet类的实例变量。

而且youngestAge应该属于您的Pet类。宠物不应该知道到目前为止其他宠物的最小年龄是多少。
youngestAge应该是其他类(如PetMain类)的成员。

您可以将其设为静态变量,然后从主类访问它,或者将其设为main方法内部的局部变量。

10-01 11:58