为什么我会收到有关从静态上下文引用非静态方法的错误?

3
在下面的代码块中,我试图打印在LettingAgent类中,与该方法参数相等的Property类中定义的location、monthlyRent和numberOfBedrooms属性。当我编译时,在if行中出现错误,其中说像getlocation()这样的非静态方法无法从静态上下文引用。
/**
 * Java coursework on class property which present detail information about the property

public class Property
{
    // instance variables of class property.
    private String address;
    private char location;
    private double monthlyRent;
    private int numberOfBedrooms;
    private boolean occupied;
    private String tenantName;

    /** 
     * Constructor for object of class Property with required parameters. 
     */
    public Property( String addressinput, char locationinput, double Rentinput, int Bedsinput )
    { 
        //initialise the instance variables or fields of property class.
        address = addressinput;
        location = locationinput;
        monthlyRent = Rentinput;
        numberOfBedrooms = Bedsinput;
        occupied = false;
        tenantName = "";
    }

    /**
     * Return the address of the property
     */
    public String getAdress( )
    {
        return address;
    }

     /**
     * Return the location of the property
     */

    public char getLocation( )
    {
        return location;
    }

     /**
     * Return the monthlyRent of the property
     */
     public double getmonthlyRent( )
    {
        return monthlyRent;
    }

     /**
     * Return the numberOfBedrooms of the property
     */
     public int getnumberOfBedrooms( )
    {
        return numberOfBedrooms;
    }

     /**
     * Return the occupied value of the property
     */
     public boolean isoccupied( )
    {
        return occupied;
    }

     /**
     * Return the tenant's name of the property
     */
     public String gettenantName( )
    {
        return tenantName;
    }

     /**
     * Set the monthly rent to a new value
     */
     public void setmonthlyRent( double newRent )
    {
       monthlyRent = newRent;
    }

     /**
     * Adding tenant's name to the property
     */
     public void addtenantName(String newTenant)
    {
        if(occupied == false) {
            tenantName = newTenant;
            occupied = true; 
        }
        else {
            System.out.println(" The property is already occupied");
        }

    }

     /**
     * Removing tenant's name of the property
     */
     public void removetenantName( )
    {
        if( occupied == true) {
            tenantName = "";
            occupied = false;
        }
        else {
            System.out.println(" The property is new and not occupied");
        }

    }

     /**
     * Print all the property attributes
     */
     public void printProperty( )
    {
        //simulate the printing of the property attributes.
       System.out.println( "The details of the property are as follow" );
       System.out.println("Address:" + address );
       switch(location){
           case 'n': case 'N': System.out.println("Location: North london" );break;
           case 's': case 'S': System.out.println("Location: South london" );break;
           case 'e': case 'E': System.out.println("Location: East london" );break;
           case 'w': case 'W': System.out.println("Location: West london" );
        } 

       System.out.println("Monthly-Rent:" + monthlyRent );
       System.out.println("Number of Bedrooms:" + numberOfBedrooms );
       System.out.println("Status of property:" + occupied );
       if(occupied == true) {
       System.out.println("Tenant Name:" + tenantName );
       }
       else {
           System.out.println("Property is empty at moment" );
        }

    }

}

LettingAgent类(调用类)

import java.util.ArrayList;

/**
 * Write a description of class LettingAgent here.
 */

public class LettingAgent
{
    // instance variables of LettingAgent Class.
    private ArrayList<Property>agproperty;
    private int Propnumber;

    /**
     * Constructor for objects of class LettingAgent
     */
    public LettingAgent()
    {
        // initialise instance variables
        agproperty = new ArrayList<Property>();
        Propnumber = 0;
    }

    /**
     * Return the property number of the Class LettingAgent. 
     */
    public int getPropnumber(){
        return Propnumber;
    }    

    /**
     *Method to add new property to the class LettingAgent via class Property.
     */
    public void addNewProperty(String addressinput, char locationinput, double Rentinput, int Bedsinput)
    {
        // put your code here
        Property newProperty = new Property(addressinput,locationinput,Rentinput,Bedsinput);
        agproperty.add(newProperty);

    }

    /**
     * @Description Method for removing the propety from the class LettingAgent.
     * @param int propnumber
     */
    public void removalOfProperty(int Propnumber)
    {
        // initialise instance variables
        if( Propnumber<agproperty.size()){
            agproperty.remove(Propnumber);
            System.out.println("The property has been removed");
        }
        else{
            System.out.println("The Property number is not valid");
        }
    }

    /**
     * Method for adding tenant to the property within class LettingAgent via class Property.
     */
    public void addTenant(int Propnumber, String newName, Property newProperty)
    {
        // initialise instance variables
        if( Propnumber<agproperty.size()){
            agproperty.get(Propnumber);
            newProperty.addtenantName(newName);
        }
        else{
            System.out.println("The Property number is not valid");
        }
    }

    /**
     * Method for removing tenant from the class LettingAgent via Property class.
     */
    public void removeTenant(int Propnumber,Property newProperty)
    {
        // initialise instance variables
        if( Propnumber<agproperty.size()){
            agproperty.get(Propnumber);
            newProperty.removetenantName( );

        }
        else{
            System.out.println("The Property number is not valid");
        }
    }

    /**
     *Method for searching property within the LettingAgent class.
     */
    public void searchProperty(String Address)
    {
        // initialise instance variables
        for(Property Property : agproperty){
            if (agproperty.get(Propnumber).equals( Address)){
                System.out.println("The details of the property is as follow"+ Property);
            }
            else{
                System.out.println("The property is not in the Letting agent's Stock");
            }
        }
    }

    /**
     * Method for printing unoccupied property of the class LettingAgent.
     */

    public void printListOfUnoccupiedProperty( char Location, double maxmonthlyRent, int miniNoBeds)
    {
        // initialise instance variables
         for(Property property : agproperty){
        if((Property.getLocation().equals(Location))&&(Property.get(monthlyRent).equals(maxmonthlyRent))&&(agproperty.get(numberOfBedrooms).equals(miniNoBeds))){
            System.out.Println(Propnumber);
            Property.printProperty();
        }
        else{
            System.out.println("The Property number is not valid");
        }
    }
    }

}

7
“做一些更正”?抱歉,这是一个问答网站,而不是一个“请纠正我的代码”网站... - fresskoma
1
其实我可能错了...Java命名规范的滥用导致语法高亮使得本不是错误的东西看起来像是错误。for(Property Property :... 我是指你。 - Mark Peters
@Bill:这个方法是在我的Property类源代码中定义的,但我没有在这里发布。你觉得如果我在这里发布整个Property类的代码会不会有问题?我感觉它会变得冗长而混乱。 - Dorji
实际上,lettingAgent类是我应该包含main方法的类,但由于我正在我的Bluej IDE中开发,所以我不需要编写这个方法。 - Dorji
@Bill:非常抱歉占用了你太多的时间。我感觉你已经回答了我的问题,但是我不知道如何查看它。希望你能告诉我。 - Dorji
显示剩余4条评论
2个回答

2
在最后一种方法中,您定义了以下格式:
/**
 * Method for printing unoccupied property of the class LettingAgent.
 */
public void printListOfUnoccupiedProperty(char Location, double maxmonthlyRent, int miniNoBeds) {
    // initialise instance variables
    for (Property Property : agproperty) {
        if ((Property.getLocation().equals(Location))
                && (Property.get(monthlyRent).equals(maxmonthlyRent))
                && (agproperty.get(numberOfBedrooms).equals(miniNoBeds))) {
            System.out.Println(Propnumber);
            Property.printProperty();
        } else {
            System.out.println("The Property number is not valid");
        }
    }
}

在线:
&& (Property.get(monthlyRent).equals(maxmonthlyRent))

您正在调用Property变量的get方法。我认为应该是Property.getMonthlyRent()

另外,Java中变量的命名应与其类名不同。我会使用类似于

for (Property property : agproperty) { ...

我知道这只是一个小改变,但它对你代码的可读性有很大影响。你可以在Java编程语言的代码规范中了解其他Java代码规范。


在下面的代码块中,我试图打印出属性,这些属性的位置、月租和卧室数量在Property类中被定义为等于此方法的参数。for (Property Property : agproperty) { if ((Property.getLocation().equals(Location)) && (P.get(monthlyRent).equals(maxmonthlyRent)) && (agproperty.get(numberOfBedrooms).equals(miniNoBeds))) - Dorji
@Dorji:请编辑问题并包括您的所有代码以及编译器给出的错误消息。 - Bill the Lizard
如果 ((Property.getLocation().equals(Location)) && (P.get(monthlyRent).equals(maxmonthlyRent)) && (agproperty.get(numberOfBedrooms).equals(miniNoBeds))) 在上面的代码块中,我试图打印出位置、月租和卧室数量与此方法参数相等的属性。当我编译时,在if行中出现错误,其中说非静态方法如getlocation()无法从静态上下文引用。 - Dorji
@Bill:抱歉搞得有点乱,但我相信我已经说明了我的问题。 - Dorji

2

好的,我已经在BlueJ中编译了您的代码,这是我发现的。首先,我收到了错误信息。

non-static method getLocation() cannot be referenced from a static context

当您将以下行中的变量名称从Property更改为property时:

for(Property property : agproperty){

你还需要更改下一行中引用它的位置:

if((Property.getLocation().equals(Location))&& ...

现在,单词 Property 只是指类名,因此表达式 Property.getLocation() 看起来像一个静态方法调用。您需要将其更改为:

if((property.getLocation().equals(Location))&& ...

请注意property的小写。
接下来还有几个方法调用需要修复,例如Property.get(monthlyRent)。你需要将变量名更改为property并放入正确的方法名。
随后我收到了错误信息:
char cannot be dereferenced

这意味着您正在尝试在char原始类型的变量上调用方法。您正在同一方法的开头执行此操作,其中包含以下内容:
property.getLocation().equals(Location) ...

由于字符是原始类型而不是对象类型,因此无法使用equals方法来比较char。 (你可以用什么来比较两个原始数据类型呢?)

当你尝试比较两个double值时,也是同样的情况。

property.getmonthlyRent().equals(maxmonthlyRent)

接下来您需要:

agproperty.get(numberOfBedrooms).equals(miniNoBeds)

这里的问题稍微有些复杂。看起来在这个短语的开头你使用了错误的变量名称。思考一下你想要比较什么,并查看你之前修复的两个问题,我相信你可以弄清楚应该在这里使用什么。


2
非常感谢您耐心地为我解答了我的冗长混乱的问题。我已经使用(==)来比较两个原始数据类型,并且它没有显示语法错误。再次感谢您 :) - Dorji

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接